Android bluetooth

监听蓝牙相关的广播并获得相关的信息,蓝牙相关的广播主要集中在BluetoothAdapterBluetoothDevice类中,

可以通过在AndroidManifest.xml中注册静态广播,也可以通过在代码中注册动态广播,两种形式的广播都可以监听到
需要相关的权限

<uses-permission android:name="android.permission.BLUETOOTH" />

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

蓝牙开关状态的广播

蓝牙的开关状态

  1.   int STATE_OFF = 10; //蓝牙关闭
  2.   int STATE_ON = 12; //蓝牙打开
  3.   int STATE_TURNING_OFF = 13; //蓝牙正在关闭
  4.   int STATE_TURNING_ON = 11; //蓝牙正在打开

对应的广播

  1.   String ACTION_STATE_CHANGED = "android.bluetooth.adapter.action.STATE_CHANGED"

监听到这个广播之后,通过intent中的EXTRA_STATE获取对应的状态值

 
 
  1.   int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,BluetoothAdapter.STATE_OFF);

打开蓝牙的广播

可以通过广播调用系统的activity来打开蓝牙,对应的广播

 
 
  1.   String ACTION_REQUEST_ENABLE = "android.bluetooth.adapter.action.REQUEST_ENABLE";
 
 
  1.   Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  2.   startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

执行这个广播之后,可以通过监听广播ACTION_STATE_CHANGED,来判断蓝牙是否打开

蓝牙扫描的广播

打开蓝牙之后,可以通过方法startDiscovery(),来扫描设备周边可以使用的其他的蓝牙设备,这个方法会触发下面的广播

  1.   String ACTION_DISCOVERY_STARTED = "android.bluetooth.adapter.action.DISCOVERY_STARTED";  //开始扫描
  2.   String ACTION_DISCOVERY_FINISHED = "android.bluetooth.adapter.action.DISCOVERY_FINISHED"; //扫描结束

如果扫描到可用的设备,还会触发广播

  1.   String ACTION_FOUND = "android.bluetooth.device.action.FOUND" //属于类 `BluetoothDevice`

注意在6.0之后的设备,如果想监听这个广播,还必须添加权限

 
 
  1.   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  2.   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

在应用中申请

  1.   ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
  2.                 android.Manifest.permission.ACCESS_FINE_LOCATION},2);

不然在6.0之后的设备中监听不到这个广播

监听到广播ACTION_FOUND,可用获得设备相关的信息

  1.   BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
  2.   String name = device.getName();  
  3.   String addr = device.getAddress();  //还有其他相关的信息

获得设备的UUID的广播

在扫描到设备之后,可用调用方法fetchUuidsWithSdp(),调用这个方法会触发这个广播

 
 
  1.   String ACTION_UUID = "android.bluetooth.device.action.UUID";

通过intent中的EXTRA_UUID,获取设备的UUID

 
 
  1.   Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);  
  2.   for (int i=0; i<uuidExtra.length; i++) {
  3.        String uuid = uuidExtra[i].toString();
  4.   }

蓝牙配对的广播

有蓝牙设备的配对请求时,会监听到这个广播

 
 
  1.   String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";

蓝牙配对状态的广播

在进行配对时,可用通过监听配对的状态判断设备是否已经配对成功配对的状态值

  1.   int BOND_NONE = 10; //配对没有成功
  2.   int BOND_BONDING = 11; //配对中
  3.   int BOND_BONDED = 12; //配对成功

广播

  1.   String ACTION_BOND_STATE_CHANGED = "android.bluetooth.device.action.BOND_STATE_CHANGED";

获取值

 
 
  1.   int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE); //当前的配对的状态
  2.   int state = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.BOND_NONE); //前一次的配对状态
  3.   BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); //配对的设备信息

蓝牙连接状态的广播

配对之后,连接设备可以通过监听下面的广播,判断设备是否连接成功

连接的状态值

  1.   int STATE_DISCONNECTED = 0; //未连接
  2.   int STATE_CONNECTING = 1; //连接中
  3.   int STATE_CONNECTED = 2; //连接成功

广播

  1.   String ACTION_CONNECTION_STATE_CHANGED = "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED";

获取值

 
 
  1.   int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, BluetoothAdapter.ERROR); //当前的连接状态
  2.   int state = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_CONNECTION_STATE, BluetoothAdapter.ERROR); //前一次的连接状态
  3.   BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); //连接的设备信息

蓝牙设备的名字变化的广播

  1.   String ACTION_LOCAL_NAME_CHANGED = "android.bluetooth.adapter.action.LOCAL_NAME_CHANGED" ; //本地设备的蓝牙设备的名称变化 `BluetoothAdapter`
  2.   String ACTION_NAME_CHANGED = "android.bluetooth.device.action.NAME_CHANGED" ;// 远程设备的名称的

开发流程

 Declare permission for library

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

• Declare BluetoothSPP like this

BluetoothSPP bt = new BluetoothSPP(Context);

• Check if bluetooth is now available

if(!bt.isBluetoothAvailable()) {
    // any command for bluetooth is not available
}

• Check if bluetooth is not enable when activity is onStart

public void onStart() {
    super.onStart();
    if(!bt.isBluetoothEnable()) {
        // Do somthing if bluetooth is disable
    } else {
        // Do something if bluetooth is already enable
    }
}

• if bluetooth is ready call this method to start service

For connection with android device

bt.startService(BluetoothState.DEVICE_ANDROID);

Communicate with android

For connection with any microcontroller which communication with bluetooth serial port profile module

bt.startService(BluetoothState.DEVICE_OTHER);

Communicate with microcontroller

Bluetooth module with SPP

• Stop service with

bt.stopService();

• Intent to choose device activity

Intent intent = new Intent(getApplicationContext(), DeviceList.class);
startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);

don't forget declare library activty like this

<activity android:name="app.akexorcist.bluetoothspp.DeviceList" />

• After intent to choose device activity and finish that activity. You need to check result data on onActivityResult

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) {
        if(resultCode == Activity.RESULT_OK)
            bt.connect(data);
    } else if(requestCode == BluetoothState.REQUEST_ENABLE_BT) {
        if(resultCode == Activity.RESULT_OK) {
            bt.setupService();
            bt.startService(BluetoothState.DEVICE_ANDROID);
            setup();
        } else {
            // Do something if user doesn't choose any device (Pressed back)
        }
    }
}

• If you want to send any data. boolean parameter is mean that data will send with ending by LF and CR or not. If yes your data will added by LF & CR

bt.send("Message", true);

or

bt.send(new byte[] { 0x30, 0x38, ....}, false);

• Listener for data receiving

bt.setOnDataReceivedListener(new OnDataReceivedListener() {
    public void onDataReceived(byte[] data, String message) {
        // Do something when data incoming
    }
});

• Listener for bluetooth connection atatus

bt.setBluetoothConnectionListener(new BluetoothConnectionListener() {
    public void onDeviceConnected(String name, String address) {
        // Do something when successfully connected
    }

    public void onDeviceDisconnected() {
        // Do something when connection was disconnected
    }

    public void onDeviceConnectionFailed() {
        // Do something when connection failed
    }
});

• Listener when bluetooth connection has changed

bt.setBluetoothStateListener(new BluetoothStateListener() {                
    public void onServiceStateChanged(int state) {
        if(state == BluetoothState.STATE_CONNECTED)
            // Do something when successfully connected
        else if(state == BluetoothState.STATE_CONNECTING)
            // Do something while connecting
        else if(state == BluetoothState.STATE_LISTEN)
            // Do something when device is waiting for connection
        else if(state == BluetoothState.STATE_NONE)
            // Do something when device don't have any connection
    }
});

• Using auto connection

bt.autoConnect("Keyword for filter paired device");

• Listener for auto connection

bt.setAutoConnectionListener(new AutoConnectionListener() {
    public void onNewConnection(String name, String address) {
        // Do something when earching for new connection device
    }
            
    public void onAutoConnectionStarted() {
        // Do something when auto connection has started
    }
});

• Customize device list's layout by create layout which include

list view with id name = "list_devices"

button with id name = "button_scan"

Example

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FDE182" >

    <ListView
        android:id="@+id/list_devices"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="20dp"
        android:smoothScrollbar="true" />
        
    <Button
        android:id="@+id/button_scan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:padding="20dp"
        android:background="#FFC600"
        android:text="SCAN"
        android:textSize="25sp"
        android:textColor="#7A481B"
        android:textStyle="bold" />
        
</RelativeLayout>

Custom Device List Layout

But if you don't need to create layout file. You just want to change only text on device list layout. You can use bundle to change text on device list

Custom Device List Text

Custom Device List Text

Custom Device List Text

Custom Device List Text

Intent intent = new Intent(getApplicationContext(), DeviceList.class);
intent.putExtra("bluetooth_devices", "Bluetooth devices");
intent.putExtra("no_devices_found", "No device");
intent.putExtra("scanning", "กำลังทำการค้นหา");
intent.putExtra("scan_for_devices", "Search");
intent.putExtra("select_device", "Select");
startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);

Custom Device List Text

https://github.com/akexorcist/Android-BluetoothSPPLibrary

猜你喜欢

转载自blog.csdn.net/liudongdong19/article/details/81050382