Recently, with the popularity of smart wearable equipment, intelligent medical care and intelligent home, Bluetooth development is very important in moving. Because of the company's needs, we studied the Bluetooth 4.0 application in Android.
Here are some of my summaries.
1. Let me introduce some of the nouns in Bluetooth 4.0:
(1), GATT (gneric attibute profile)
Through BLE connection, reads and writes the attribute class small Data Profile general specification. Now all BLE application profiles are based on the GATT
(2), ATT (Attribute protocal)
The GATT is based on the att potocal att for ble devices specifically for the transmission process using as little data as possible, each attribute has a unique uuid, attributes Chartcteristics and service form transmission.
(3), service is a collection of characteristic.
(4), characteristic feature type.
For example, there is a Bluetooth ble sphygmomanometer. He may include multiple servvice, each service includes multiple characteristic
Note: bluetooth ble can only support more than 4.3 of Android systems sdk>=18
2. The following steps have been developed:
2.1 First Get Bluetoothmanager
Copy Code code as follows:
Bluetoothmanager Bluetoothmanager = (bluetoothmanager) getsystemservice (Context.bluetooth_service);
2.2 Get Bluetoothadapter
Copy Code code as follows:
Bluetoothadapter mbluetoothadapter = Bluetoothmanager.getadapter ();
2.3 Creating Bluetoothadapter.lescancallback
Private Bluetoothadapter.lescancallback Mlescancallback = new Bluetoothadapter.lescancallback () {
@Override
public void Onlescan (final bluetoothdevice device, int rssi, final byte[] scanrecord) {
runonuithread (new Runnable () {
@Override public
void Run () {
try {
String struuid = numberutils.bytes2hexstring ( Numberutils.reversebytes (Scanrecord)). Replace ("-", ""). toLowerCase ();
if (Device!=null && struuid.contains (Device_uuid_prefix.tolowercase ())) {
Mbluetoothdevices.add (device );
}
} catch (Exception e) {
e.printstacktrace ();}}}
);
2.4. Start the search device.
Copy Code code as follows:
Mbluetoothadapter.startlescan (Mlescancallback);
The
2.5.bluetoothdevice describes a Bluetooth device that provides the name of the getaddress () device MAC address, GetName () device.
2.6 Start connecting devices
/** * Connects to the GATT server hosted on the Bluetooth LE device.
* * @param address * The device address of the destination device. * @return return TRUE if the connection is initiated successfully. The * connection result is reported asynchronously through the * {@code Bluetoothgattcallback#onconnectionstatec
Hange (android.bluetooth.BluetoothGatt, int, int)} * callback. * Public boolean Connect (final String address) {if (Mbluetoothadapter = null | | | address = NULL) {LOG.W (TAG,
"Bluetoothadapter not initialized or unspecified address.");
return false; }//previously connected device. Try to reconnect. (The previously connected device.) Attempt to reconnect) if (mbluetoothdeviceaddress!= null && address.equals (mbluetoothdeviceaddress) && Mbluetoothga
tt!= NULL) {LOG.D (TAG, "trying to use a existing mbluetoothgatt for connection.");
if (Mbluetoothgatt.connect ()) {mconnectionstate = state_connecting;
return true; else {return false;
} final Bluetoothdevice device = Mbluetoothadapter.getremotedevice (address); if (device = null) {LOG.W (TAG, "device not found.)
Unable to connect. ");
return false;
//We want to directly connect to the device and so We are setting the "//AutoConnect//parameter to FALSE.
Mbluetoothgatt = Device.connectgatt (this, false, mgattcallback);
LOG.D (TAG, "trying to create a new connection.");
mbluetoothdeviceaddress = address;
Mconnectionstate = state_connecting;
return true;
}
2.7 After connecting to the device, obtain the characteristic for the service and service of the device.
Demonstrates to iterate through the supported GATT//Services/characteristics.
In this sample, we populate the "Data structure" the "is bound to the"//Expandablelistview//on the UI.
private void Displaygattservices (list<bluetoothgattservice> gattservices) {if (gattservices = = null) return;
String uuid = null;
arraylist
2.8 After acquiring the feature, locate the feature in the service that can write to the down-level machine and write instructions to the feature.
public void wirtecharacteristic (bluetoothgattcharacteristic characteristic) {
if (Mbluetoothadapter = = NULL | | Mbluetoothgatt = = null) {
LOG.W (TAG, "Bluetoothadapter not Initialized");
return;
}
Mbluetoothgatt.writecharacteristic (characteristic);
}
2.9 After the write is successful, the data returned from the device is read.
Private final Bluetoothgattcallback mgattcallback = new Bluetoothgattcallback () {@Override public void Onconnectio
Nstatechange (Bluetoothgatt GATT, int status, int newstate) {String intentaction;
System.out.println ("=======status:" + status);
if (newstate = = bluetoothprofile.state_connected) {intentaction = action_gatt_connected;
Mconnectionstate = state_connected;
Broadcastupdate (intentaction);
LOG.I (TAG, "Connected to GATT server.");
Attempts to discover services after successful connection.
LOG.I (TAG, "attempting to start service discovery:" + mbluetoothgatt.discoverservices ());
else if (newstate = = bluetoothprofile.state_disconnected) {intentaction = action_gatt_disconnected;
Mconnectionstate = state_disconnected;
LOG.I (TAG, "Disconnected from GATT server.");
Broadcastupdate (intentaction); @Override public void onservicesdiscovered (Bluetoothgatt gatt, int status) {if (status = = bluetoothgatt.gatt_success) {broadcastupdate (action_gatt_services_discovered);
else {LOG.W (TAG, "onservicesdiscovered Received:" + status); ///Read data from feature @Override public void Oncharacteristicread (Bluetoothgatt GATT, Bluetoothgattcharacteristic Char
acteristic, int status) {//system.out.println ("Oncharacteristicread");
if (status = = Bluetoothgatt.gatt_success) {broadcastupdate (action_data_available, characteristic); Write data to the feature @Override public void Oncharacteristicwrite (Bluetoothgatt GATT, Bluetoothgattcharacteristic Cha
racteristic, int status) {//system.out.println ("--------Write success-----Status:" + status); }/* When connected successfully'll callback this method can * Dealwith send password or data Analyze * When the connection succeeds will callback the method * * * @Override public void oncharacteristicchanged (Bluetoothgatt GATT, Bluetoothgatt Characteristic characteristic) {broadcastupdate (Action_data_available, characteristic);
if (Characteristic.getvalue ()!= null) {//system.out.println (characteristic.getstringvalue (0));
}//system.out.println ("--------oncharacteristicchanged-----");
@Override public void Ondescriptorwrite (Bluetoothgatt GATT, bluetoothgattdescriptor descriptor, int status) { System.out.println ("Ondescriptorwriteondescriptorwrite =" + Status + ", descriptor =" + Descriptor.getuuid (). Tostri
Ng ());
UUID uuid = descriptor.getcharacteristic (). Getuuid ();
if (Uuid.equals (uuid.fromstring ("0000CD01-0000-1000-8000-00805F9B34FB"))) {broadcastupdate (ACTION_CD01NOTIDIED); else if (Uuid.equals (uuid.fromstring ("0000CD02-0000-1000-8000-00805F9B34FB"))) {Broadcastupdate (ACTION_CD02NOTID
IED); else if (Uuid.equals (uuid.fromstring ("0000CD03-0000-1000-8000-00805F9B34FB"))) {Broadcastupdate (ACTION_
cd03notidied); else if (Uuid.equals (uuid.fromstring ("0000CD04-0000-1000-8000-00805F9B34FB"))) {broadcastupdate (action_cd04notidied); @Override public void Onreadremoterssi (Bluetoothgatt GATT, int rssi, int status) {//system.out.println
("Rssi =" + Rssi);
}
}; ----------------------------------------------//Read data from the feature @Override public void Oncharacteristicread (Bluetoothgat
T GATT, bluetoothgattcharacteristic characteristic, int status) {//system.out.println ("Oncharacteristicread");
if (status = = Bluetoothgatt.gatt_success) {broadcastupdate (action_data_available, characteristic);
}
}
2.10. Disconnect the connection
/**
* Disconnects an existing connection or cancel a pending connection. The
* disconnection result is reported asynchronously through the
* {@code bluetoothgattcallback# Onconnectionstatechange (android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/public
void Disconnect () {
if (Mbluetoothadapter = null | | | mbluetoothgatt = NULL) {
LOG.W (TAG, "Bluetooth Adapter not initialized ");
return;
}
Mbluetoothgatt.disconnect ();
}
2.11, the Data conversion method
Byte to hexadecimal string public
static string bytes2hexstring (byte[] bytes) {
string ret = ' ";
for (byte abyte:bytes) {
String hex = integer.tohexstring (Abyte & 0xFF);
if (hex.length () = = 1) {
hex = ' 0 ' + hex;
}
RET + hex.touppercase (Locale.china);
}
return ret;
}
/**
* Converts a 16-binary string to a byte array
*
* @param message
* @return byte array
/public static byte[] Gethexbytes ( String message) {
int len = Message.length ()/2;
char[] chars = Message.tochararray ();
string[] hexstr = new String[len];
byte[] bytes = new Byte[len];
for (int i = 0, j = 0; j < len; i = 2, j + +) {
Hexstr[j] = "" + chars[i] + chars[i + 1];
BYTES[J] = (byte) integer.parseint (Hexstr[j];
}
return bytes;
Probably the whole is as the step, but also to be specific according to the manufacturer's agreement to achieve the communication process.
Just take a demo of our project.
A bluetooth ble sphygmomanometer. PC---Mobile device--Sphygmomanometer
1. The sphygmomanometer is connected with the mobile phone after Bluetooth.
2. The upper machine active downward position machine sends an authentication instruction, the subordinate machine receives the instruction to begin to answer to the superior,
3. Response success, the next opportunity to measure the blood pressure data to the host computer.
4. Finally disconnect.
I hope this article will help you learn about Android Bluetooth technology.