Get Permissions
<android:name= "Android.permission.BLUETOOTH"/>< android:name= "Android.permission.BLUETOOTH_ADMIN"/>
Get an instance of the Bluetooth adapter
Final Bluetoothmanager Bluetoothmanager = = Bluetoothmanager.getadapter ();
BLE search: Instantiate callback function, start/stop scan
1. Instantiate callback function
PrivateBluetoothadapter.lescancallback Mlescancallback =NewBluetoothadapter.lescancallback () {@Override Public voidOnlescan (FinalBluetoothdevice device,intRssi,byte[] scanrecord) {Runonuithread (NewRunnable () {@Override Public voidrun () {//get a Bluetooth device instance } }); }};
2. Start/Stop Scan
Mbluetoothadapter.startlescan (mlescancallback); // Start scanning mbluetoothadapter.stoplescan (mlescancallback); // Stop Scanning
BLE connection: Instantiate callback function, connect and bind callback function
1. Instantiate callback function
Private FinalBluetoothgattcallback Mgattcallback =NewBluetoothgattcallback () {//triggers when the connection state changes@Override Public voidOnconnectionstatechange (Bluetoothgatt GATT,intstatus,intnewstate) {String intentaction; if(NewState = =bluetoothprofile.state_connected) { //when the Bluetooth device is connected ... } Else if(NewState = =bluetoothprofile.state_disconnected) { //when the device cannot connect ... } } //triggers when new services are discovered@Override Public voidOnservicesdiscovered (Bluetoothgatt GATT,intstatus) { if(Status = =bluetoothgatt.gatt_success) { ... } Else { ... } } //read/write features@Override Public voidOncharacteristicread (Bluetoothgatt GATT, bluetoothgattcharacteristic characteristic,
intstatus) { if(Status = =bluetoothgatt.gatt_success) { ... } } ... };
2. Get the Bluetooth device instance and connect to the Bluetooth device instance.
The Bluetooth address instantiates a Bluetooth device, or passes a reference through the above scan. final bluetoothdevice device = mbluetoothadapter.getremotedevice (address);
// three parameters involved: a context object, an auto-connect (Boolean value that indicates that the BLE device is automatically connected to it if it is available), and the Bluetoothgattcallback call. Private Bluetoothgatt Mbluetoothgatt = Device.connectgatt (thisfalse, Mgattcallback) ;
Key steps in BLE programming