In my last two articles blog post explained about Android Bluetooth awareness as well as APIs related to the introduction of Bluetooth ble search, connection and read.
Do not know the children's shoes, please refer to:
Learn more about the basics of Android Bluetooth bluetooth--
Learn more about the Android Bluetooth bluetooth--"Advanced article"
Currently in the project:
Next we will summarize the Bluetooth BLE4.0.
Bluetooth API
Android ble bluetooth 4.0, that is, API level >= 18, and support Bluetooth 4.0 mobile phone can be used, if the mobile System version API level < 18, but also not use Bluetooth 4.0 OH
1. Bluetoothgatt
2. bluetoothgattcharacteristic
3. Bluetoothgattdescriptor
描述符,对Characteristic的描述,包括范围、计量单位等
Bluetoothgattservice
A collection of services, characteristic.
Bluetoothprofile
A generic specification for sending and receiving data according to this specification.
Bluetoothmanager
Get Bluetoothadapter with Bluetoothmanager
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
Bluetoothadapter
An Android system has only one bluetoothadapter, which gets through Bluetoothmanager
BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();1.8 BluetoothGattCallback
The
has been connected to the device after certain operations on the device have returned results. Here must be reminded that after the device has been connected to return, did not return to seriously see if there is no connection on the device.
private bluetoothgattcallback Gattcallback = new bluetoothgattcallback () {// Here are 9 ways to implement it, to see what happens, to implement those public void onconnectionstatechange (Bluetoothgatt GATT, int status, int newstate) {}; public void oncharacteristicwrite (Bluetoothgatt GATT, bluetoothgattcharacteristic characteristic, int status) {};}; Bluetoothdevice device = Mbluetoothadapter.getremotedevice (address); Bluetoothgatt GATT = Device.connectgatt (this , false , Mgattcallback);
Notification Correspondence oncharacteristicchanged
true);
Readcharacteristic Correspondence Oncharacteristicread
gatt.readCharacteristic(characteristic);
- Writecharacteristic Correspondence Oncharacteristicwrite
gatt.wirteCharacteristic(mCurrentcharacteristic);
Connect bluetooth or disconnect bluetooth onconnectionstatechange
Readdescriptor corresponds to Ondescriptorread;
Writedescriptor corresponds to Ondescriptorwrite;
gatt.writeDescriptor(descriptor);
- Readremoterssi Correspondence Onreadremoterssi
gatt.readRemoteRssi()
Executereliablewrite corresponds to onreliablewritecompleted;
Discoverservices Correspondence onservicesdiscovered
gatt.discoverServices()
- Bluetoothdevice
Discover connected devices after scanning to get connected devices
Second, turn on Bluetooth permissions
<uses-permission android:name="android.permission.BLUETOOTH"/><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/><uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
Android ble bluetooth 4.0, that is, API level >= 18, and Bluetooth 4.0 mobile phone can be used, if the phone system version API level < 18, is not used Bluetooth 4.0
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText"设备不支持蓝牙4.0", Toast.LENGTH_SHORT).show(); finish();}
or a
// 检查当前手机是否支持blue 蓝牙,如果不支持退出程序 if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { showToast("不支持蓝牙4.0通讯"); return; } mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); // 检查设备上是否支持蓝牙 ifnull) { showToast("没有发现蓝牙模块"); return; }
Third, the start and close operation of Bluetooth
- IsEnabled ()
Returns true if local Bluetooth is in a usable state (such as Bluetooth on the phone)
- GetState ()
Get Bluetooth status generally have bluetoothadapter.state_ble_on, state_ble_turning_on, State_ble_turning_off, State_off
- Enable ()
Turn on the Bluetooth device, this is not friendly, it is recommended to use the following methods
Intent Intent = new Intent (bluetoothadapter.action_request_enable);
Startactivityforresult (Intent,open_request_code);
There's a pop-up window that prompts the user whether to turn on Bluetooth
- Disable ()
Turn off the local Bluetooth service after closing all Bluetooth connections
- GetAddress ()
Get Bluetooth MAC Address
- GetName ()
Get the Bluetooth name, also the Bluetooth name we often set
- SetName ()
Set Bluetooth name
- StartDiscovery ()
Start discovering devices (note that the device, such as another phone, is not a Bluetooth headset, etc.)
- Getbondeddevices ()
Gets the device that is bound (paired), and the test finds that only a manual unbind is working, or even if Bluetooth is turned off, the interval is still bound.
At the same time some bound devices (such as the bracelet) do not return the corresponding device with this method
- Startlescan (Lescancallback)
Start scanning the Bluetooth LE devices device (bluetooth headset, bracelet, electronic weigh, etc.). The callback function returns the device that is being scanned,
Note that the device will be scanned repeatedly, it is best to remove the repetition, the deduplication can be used with the MAC address, or the name, but the scan to the device for the first time did not
Name is brought back, so it's best to make a non-null judgment when getting the name
- Stoplescan (Lescancallback)
Stop scanning
- > Using the system default to turn on the Bluetooth dialog box
ifnull || !mBluetoothAdapter.isEnabled()) { new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);}
Bluetoothgatt about the Android Bluetooth service class
Generic Attribute Profile (GATT)-the GATT Profiles are a general specification for sending and receiving short
Pieces of data known as "attributes" over a BLE link. All application profiles is based on
GATT. The master-slave equipment maintains the GATT, respectively, client and server
Gets the method that is returned when the connection is created
mConnGatt = bleDevie.connectGatt(this, false, mGattcallback);
Callback
public abstract class BluetoothGattCallback { public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { } public void onServicesDiscovered(BluetoothGatt gatt, int status) { } public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { } public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { }
Set up Notifications
public boolean setCharacteristicNotification(UUID serviceUuid, UUID characteristicUuid, boolean enable) { BluetoothGattCharacteristic characteristic = mConnGatt.getService(serviceUuid).getCharacteristic(characteristicUuid); mConnGatt.setCharacteristicNotification(characteristic, enable); BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID); descriptor.setValue(enable ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : new byte[]{0x00, 0x00}); return mConnGatt.writeDescriptor(descriptor); // descriptor write}
Once encountered the pit
- Bluetooth timed out on a consecutive time
Workaround:
Reconnect in the appropriate method on the broadcast
PrivateFinal Broadcastreceiver Mgattupdatereceiver= NewBroadcastreceiver () {@Override Public voidOnReceive (context context, Intent Intent) {finalStringAction=Intent.Getaction ();if(Bluetoothleservice.action_gatt_connected.equals(action)) {//Bluetooth is connectedTvbluetooth.SetText ("(connected)"); }Else if(Bluetoothleservice.action_gatt_disconnected.equals(action)) {Showtoast ("Bluetooth connection disconnected, please try again");//Reconnect the Bluetooth connection hereHideloading (); }Else if(Bluetoothleservice.Action_gatt_services_discovered.equals(action)) {//Discover Bluetooth, set command ......}Else if(Bluetoothleservice.Action_data_available.equals(action)) {//Received Data ......} } };
- Bluetooth search to match does not come with BLE device
Some hand performance is relatively low-end, here can restart Bluetooth, to reconnect
- ##### Disconnect after successful connection
- Ensure that the BLE device is not connected by another
- Stop scanning first-"rescan-" reconnect
- Bluetooth disconnected during read
The first thing to do is to ensure that the last time the connection was disconnected before connecting to Bluetooth:
- Disconnect Connection
- Disconnect (Close) service
- Turn off Bluetooth
Then execute:
Stop scanning first-"rescan-" reconnect
- ##### Uploading data failed
After parsing the read data, save it locally and upload it the next time you upload it. Remember to erase this low data after uploading successfully.
Note: Ble bluetooth connection Small device generally belongs to the master-slave module, wherein the main module Bluetooth can connect multiple devices simultaneously, but read only one. Related items: Http://download.csdn.net/detail/lqw770737185/8116019GitHub download Link: https://github.com/androidstarjack/ Bluetooth_4.3-master
Next, we recommend two learning URLs for Bluetooth ble on Android:
Detailed API for detailed parsing of Bluetoothadapter
Http://www.open-open.com/lib/view/open1390879771695.html
Android: Bluetooth 4.0-ble-Summary =1.0
Http://www.itnose.net/detail/6095842.html
If you think this article is helpful to you, welcome to QQ Group: 232203809??
Public Number: Terminal Research and Development department
(Welcome to learn and Exchange)
Learn more about Android Bluetooth bluetooth--"Summary"