Android Bluetooth 4.0 Development
1. Permissions and related attributes
"android:required=" true "means that the APK is only running on a system with Bluetooth_le properties, and this 4.3 before the Android system
<uses-featureandroid:name= "Android.hardware.bluetooth_le" android:required= "true"/>
<uses-permissionandroid:name= "Android.permission.BLUETOOTH"/>
<uses-permissionandroid:name= "Android.permission.BLUETOOTH_ADMIN"/>
2, the program to open the mother to operate Bluetooth before the first to determine whether BLE support
if (!getpackagemanager (). Hassystemfeature (Packagemanager.feature_bluetooth_le)) {
Toast.maketext (this,r.string.ble_not_supported, Toast.length_short). Show ();
Finish ();
}
3. Turn Bluetooth on and off
Get a proxy for Bluetooth first
Final Bluetoothmanager Bluetoothmanager =
(Bluetoothmanager) Getsystemservice (Context. Bluetooth_service);
Mbluetoothadapter = Bluetoothmanager.getadapter ();
Send intent notification system to turn on Bluetooth
if (!mbluetoothadapter.isenabled ()) {
if (!mbluetoothadapter.isenabled ()) {
Intent enablebtintent = newintent (bluetoothadapter.action_request_enable);
Startactivityforresult (Enablebtintent, REQUEST_ENABLE_BT);
}
}
You can also use the Enable and disable functions to turn off
4. Search for BLE devices
Mhandler.postdelayed (Newrunnable () {
@Override
public void Run () {
Mscanning = false;
Mbluetoothadapter.stoplescan (Mlescancallback);
}
}, Scan_period);
Mscanning = true;
Mbluetoothadapter.startlescan (Mlescancallback);
Scan_period is 10000, which means the search time is 10 seconds each time.
It is important to note that the API before 4.3 is the event that occurs when the Mlescancallback is registered for broadcasting to process the search, while the new API that supports BLE is handled by a callback, and Mlescancallback is an interface object that looks at the implementation:
Privatebluetoothadapter.lescancallback Mlescancallback =
Newbluetoothadapter.lescancallback () {
@Override
public void Onlescan (finalbluetoothdevice device, int rssi, byte[] scanrecord) {
Runonuithread (New Runnable () {
@Override
public void Run () {
Mledevicelistadapter.adddevice (device);
Mledevicelistadapter.notifydatasetchanged ();
}
});
}
};
5. Connection
4.3 Before the API is through the socket to communicate with each other in Bluetooth, the result of the connection is to return a socket object
In the new API that supports 4.0 Bluetooth, the Bluetoothgatt object is returned
You can treat a Bluetoothgatt object as a proxy for a remote device
Mbluetoothgatt = Device.connectgatt (this, false,mgattcallback);
Mgattcallback is an abstract class object, and the previous broadcast form has been changed to a callback in the new API.
Bluetoothgattcallback abstract class, only 9 methods, the literal meaning can be understood, in the processing of connection events, the need to deal with the method:
Public Voidonconnectionstatechange (Bluetoothgatt GATT, int status,
Intnewstate)
Condition: if (newstate ==bluetoothprofile.state_connected)
else if (newstate ==bluetoothprofile.state_disconnected) indicates connected and disconnected, respectively
6. Communication
This is completely different from the previous form.
BLE is divided into three parts service, characteristic, and descriptor, all of which are identified by the UUID as a unique identifier. A Bluetooth 4.0 terminal can contain multiple service, one service can contain multiple characteristic, one characteristic contains one value and multiple descriptor, and one descriptor contains a value.
After connecting to a terminal, you can print each of its node's UUID, but each node can not read and write.
In general, characteristic is the key to the exchange of data between the phone and the BLE terminal, characteristic has more rights-related fields, such as permission and property, the most commonly used is the property, The BLE bluetooth module used in this article has no standard characteristic permission. The property of characteristic can be set to read and write properties by combining bitwise operators, such as read| WRITE, read| write_no_response| NOTIFY, so the property is read and decomposed into the combination used
I am going to communicate with the BLE terminal in this way:
Get an object for a service
Bluetoothgattservice Linklossservice =mbluetoothgatt
. GetService (Uuid.fromstring ("49535343-fe7d-4ae5-8fa9-9fafd205e455"));
In general, BLE devices are provided with several standard services, the UUID has been defined, the values in these nodes can only be read, because I tried one, and finally found my device can read and write services, 49535343-fe7d-4ae5-8fa9-9fafd205e455 is the one that corresponds to this service.
Gets a characteristic object under this service node.
Bluetoothgattcharacteristic alertlevel =linklossservice.getcharacteristic (uuid.fromstring (" 49535343-8841-43f4-a8d4-ecbe34729bb3 "));
The general supplier will give a number of characteristic, you need to find out exactly which is let you write, how to find the corresponding terminal to see some development documentation and so on, I have been tested here to find what I want
Set the value to write
Alertlevel.setvalue (values_on);
The values_on here is a byte array
Write
Status = Mbluetoothgatt.writecharacteristic (Alertlevel);
Status if true, indicates that the write operation has executed successfully, a method of Bluetoothgattcallback abstract class will be executed, and if you rewrite this method again, you can print some messages.
Public void Oncharacteristicwrite (Bluetoothgatt GATT,
bluetoothgattcharacteristiccharacteristic, int status)
Read a characteristic
Public void readcharacteristic (bluetoothgattcharacteristiccharacteristic) {
if (Mbluetoothadapter = = Null | | mbluetoothgatt = = null) {
Log. W (TAG, "Bluetoothadapter not initialized");
return;
}
Mbluetoothgatt.readcharacteristic (characteristic);
}
If successful, the data is passed in the following method callback
Public Voidoncharacteristicread (Bluetoothgatt GATT,
Bluetoothgattcharacteristic characteristic,
int status)
When the terminal has data to pass over, on the surface of normal, the phone side of the following method will be called
Public Voidoncharacteristicread (Bluetoothgatt GATT,
Bluetoothgattcharacteristic characteristic,
Intstatus)
This is also controllable, set the value of the descriptor is different, you can control whether the overridden method will be called, do not test other devices, it is supposed to be a different device, the specific settings of the place will be different, on my side is so operation:
public void EnableNotification (Boolean b)
{
if (b)
{
Bluetoothgattservice Service =mbluetoothgatt
. GetService (Uuid.fromstring ("49535343-fe7d-4ae5-8fa9-9fafd205e455"));
Bluetoothgattcharacteristicale =service.getcharacteristic (uuid.fromstring ("49535343-1e4d-4bd9-ba61-23c647249616 "));
Booleanset = Mbluetoothgatt.setcharacteristicnotification (ale, True);
LOG.D (TAG, "setnotification =" + set);
BLUETOOTHGATTDESCRIPTORDSC =ale.getdescriptor (uuid.fromstring ("00002902-0000-1000-8000-00805F9B34FB"));
Byte[]bytes = {0x01,0x00};
Dsc.setvalue (bytes);
Boolean Success =mbluetoothgatt.writedescriptor (DSC);
LOG.D (TAG, "writing Enabledescriptor:" + success);
}
Else
{
Bluetoothgattservice Service =mbluetoothgatt
. GetService (Uuid.fromstring ("49535343-fe7d-4ae5-8fa9-9fafd205e455"));
Bluetoothgattcharacteristicale =service.getcharacteristic (uuid.fromstring ("49535343-1e4d-4bd9-ba61-23c647249616 "));
Booleanset = Mbluetoothgatt.setcharacteristicnotification (ale, False);
LOG.D (TAG, "setnotification =" + set);
BLUETOOTHGATTDESCRIPTORDSC =ale.getdescriptor (uuid.fromstring ("00002902-0000-1000-8000-00805F9B34FB"));
Byte[]bytes = {0x00, 0x00};
Dsc.setvalue (bytes);
Boolean Success =mbluetoothgatt.writedescriptor (DSC);
LOG.D (TAG, "writing Enabledescriptor:" + success);
}
}
7. Summary
Some of the information on the Internet is mostly identified by the above name of the document, it is necessary to explain, should be divided to see this proposition:
Android refers to devices that are installed on Android systems of version 4.3 and above
4.0 Bluetooth refers to the Bluetooth chip using the 4.0 protocol device
One of the standard uses of this development is to communicate with 4.0 Bluetooth wearable devices with more than 4.3 Android versions of mobile phones.
According to a central and peripheral network, mobile phone is the central, 4.0 Bluetooth devices on the periphery
If you want to develop 4.0 Bluetooth, you should know that 4.0 Bluetooth has the advantages of high speed, low power consumption, these advantages on the mobile phone, but the promotion of some other terminal equipment is relatively large.
Interestingly, Android to the package with 4.0 Bluetooth communication, does not need the Bluetooth chip of its own device is the 4.0 protocol Bluetooth chip
So the Android Bluetooth 4.0 development of such a "big environment" under the real situation is: a no need to have Bluetooth 4.0 protocol Bluetooth chip android4.3 above the system of mobile phones, with some 4.0 Bluetooth protocol Bluetooth chip device terminal story
These are some facts, and here are some speculations
1, Bluetooth 4.0 and the previous version of the Protocol can be communicated, that: 4.0 Bluetooth protocol is not modified wireless wave modulation and demodulation, but the composition of the modified data
2. The Bluetooth 4.0 protocol support, is proposed by Google, rather than the various mobile phone manufacturers, explained: Android system in the software can be consistent treatment of different Bluetooth chips, different Bluetooth chip on the same piece of data modulation and demodulation results are the same, so in this section of the data through a series of oral control of the master, it is the same, in this Environment, the Bluetooth chip is just a modem, and Android encapsulates all the processing of the data.
Android ble bluetooth development a little solution