In [Learn more about Android Bluetooth bluetooth--Basics] (http://blog.csdn.net/androidstarjack/article/details/60468468) One of the various versions of Bluetooth has a knowledge of the Bluetooth version of the course and the advantages and disadvantages of the introduction. So let's go into the next step and drive into the BLE chapter. Bluetooth ble4.xble is divided into three parts:
-
Service
-
Characteristic
-
Descriptor
All three parts use the UUID as a unique identifier. The UUID is in this format: 0000FFE1-0000-1000-8000-00805F9B34FB. For example, there are 3 service, then there are three different UUID corresponding to the service. These uuid are written in the hardware, we can read through the API provided by BLE.
- A ble terminal can contain multiple service, one service can contain multiple characteristic, one characteristic contains one value and multiple descriptor, A descriptor contains a value. Characteristic is more important, is the mobile phone and BLE terminal Exchange Data key, reading settings data and other operations are the relevant properties of the operation characteristic.
API Related Introduction
-
1. Let's introduce some of the nouns in Bluetooth 4.0:
(1) GATT (gneric attibute profile)
Through BLE connection, read-write attribute class small Data profile generic specification. All BLE application profiles are now based on the GATT
- (2) Att (Attribute protocal) GATT is a att potocal-based att specifically for BLE devices specifically, the transfer process uses as little data as possible, each property has a unique UUID, properties Chartcteristics and Service in the form of a transmission.
- (3) The service is a collection of characteristic.
- (4). The characteristic feature type.
Like what. There is a Bluetooth ble sphygmomanometer. He may include multiple servvice, each service has multiple characteristic included
Note: Bluetooth ble can only support Android 4.3 and above system sdk>=18
-
2. The following are the steps for development:
-
2.1 First Get Bluetoothmanager
-
2.2 Get Bluetoothadapter
-
2.3 Creating Bluetoothadapter.lescancallback
-
2.4. Start searching for devices.
-
2.5.BluetoothDevice describes a Bluetooth device that provides the name of the getaddress () device MAC address, GetName () device.
-
2.6 Start connecting the device
-
2.7 After connecting to the device, get the service of the device and the characteristic that corresponds to the service.
-
2.8 After the feature is acquired, locate the feature in the service that can be written down to the command, and write instructions to the feature.
-
2.9 After the write succeeds, read the data returned by the device.
-
2.10. Disconnect the connection
-
2.11, the Data conversion method
Probably the whole is like the steps above. But it is also to be specific according to the manufacturer's agreement to achieve the process of communication.
So how exactly do you use it? We need to drive down the road.
One. Add Permissions
? Like classic Bluetooth, apps use Bluetooth, you need to declare Bluetooth permissions, and if you need to scan your device or operate Bluetooth settings, you'll also need Bluetooth_admin permissions:
<uses-permission android:name="android.permission.BLUETOOTH"/><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
In addition to Bluetooth permissions, if you need ble feature you also need to declare uses-feature:
android:name="android.hardware.bluetooth_le" android:required="true"/>
On time required is true, the app can only be installed on an Android device that supports BLE, and when required is false, Android devices are installed and run, and you need to determine if your device supports BLE feature when your code is running:
// Use this check to determine whether BLE is supported on the device. Then// you can selectively disable BLE-related features.if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show(); finish();}
First step: Turn on Bluetooth:
- 1. There are two ways to get Bluetoothadapter first:
private BluetoothManager bluetoothManager;bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);mBluetoothAdapter = bluetoothManager.getAdapter();
Or is:
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Both lines are OK.
Note: Get Bluetoothmanager through Getsystemservice and get bluetoothadapter through Bluetoothmanager. Bluetoothmanager above Android4.3 support (API level 18).
- 2. Determine if the mobile device has a Bluetooth module
// 检查设备上是否支持蓝牙 if (mBluetoothAdapter == null) { showToast("没有发现蓝牙模块"); return; }
-
3. Turn on the Bluetooth device
There are two ways to turn on your Bluetooth device:
- The first kind of direct simple violence does not prompt the user:
if (!mBluetoothAdapter.isEnabled()) { mBluetoothAdapter.enable();}
- The second straight elegant practice opens and has a bullet box to prompt, the implicit start intent:
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);}
-
4. Scan Bluetooth devices
I am here to store the scanned ble address in the list collection. Here we can write a method to encapsulate it.
/*********** * scan device **** ****/private void ScanLeDevice ( Final Boolean enable) {if (Build.VERSION.SDK_INT >= build.version_codes. JELLY_BEAN_MR2) {if (enable) {devices.clear ();//Empty collection//Stops scanning after a pre-defined scan period. Mhandler.postdel Ayed (New Runnable () { @Override public void run () {if (Build.VERSION.SDK_INT >= build.vers Ion_codes. JELLY_BEAN_MR2) {Mbluetoothadapter.stoplescan (mlescancallback);}} }, Interval_time); Mbluetoothadapter.startlescan (Mlescancallback); } else {try {mbluetoothadapter.stoplescan (mlescancallback);} catch (Exception e) {}}}} /span>
In this scanning method, we will see in Androidstudio or eclipse that the Startlescan method will have a horizontal line, indicating that this way shows the outdated method, then
If you only need to search the peripheral for the specified UUID, you can call the Startlescan (uuid[], Bluetoothadapter.lescancallback) method. Where the UUID array specifies the UUID of the GATT services supported by your application.
Then the Lescancallback initialization code is as follows:
PrivatevoidInitcallback(){if (Build.VERSION.SDK_INT >= build.version_codes. JELLY_BEAN_MR2) {Mlescancallback =New Bluetoothadapter.lescancallback () {@OverridePublicvoidOnlescan(Final Bluetoothdevice device,int Rssi, byte[] scanrecord) {runonuithread (new Runnable () { @Override public void run () {if (device! = null) {if (! Textutils.isempty (Device.getname ())) {//devices.add (device); String name = Device.getname (); if (Name.contains (bluetoothdeviceattr.oygen_device_name)) { if (!devices.contains (device)) {Devices.add (device);}} } } } }); } }; } else {gettoast ( "Device Bluetooth version too Low"); return;}
So if in the case of a lot of equipment we talk about the search for many devices. We can choose the address we need to link. But this kind of note is: When searching, you can only search the traditional Bluetooth device or BLE device, the two are completely independent, can not be searched at the same time.
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, so we are setting the autoConnect // parameter to false. mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
This is called the Connectgatt method of the device.
/** * ConnectTo GATT Server hostedBy this device. Caller actsAs GATT client. * The callbackis usedTo deliver resultsTo Caller, suchAs Connection statusAs well *As any further GATT client operations. * The method returns a Bluetoothgatt instance. can use BluetoothgattTo conduct * GATT client operations. * @param callback GATT Callback Handlerthat would receive asynchronous callbacks. * @param autoconnect Whether to directly connect to the Remote device (false) * or to automatically connect Span class= "Hljs-keyword" >as soon as the remote * device becomes Available (true). * @throws illegalargumentexception if Callback is null */Public Bluetoothgatt Connectgatt (context context, boolean AutoConnect, Bluetoothgattcallback callback) { Return (Connectgatt (context, Autoconnect,callback, Transport_auto));
The API illustrates that the first parameter is the context object, the second argument is whether to connect automatically, and the third is the gattcallback callback for Bluetooth.
Private Bluetoothgattcallback Gattcallback =New Bluetoothgattcallback () {Here are 9 ways to do it, to see what happens, to implement thoseWhen the connection state changes@OverridePublicvoidOnconnectionstatechange(Bluetoothgatt GATT,int status,int newstate) {};The result of the callback response feature write operation.@OverridePublicvoidOncharacteristicwrite(Bluetoothgatt GATT, bluetoothgattcharacteristic characteristic,int status) {};The result of the callback response feature read operation.@OverridePublicvoidOncharacteristicreadint status) {} //the result of the callback when the service was found @Override public void onservicesdiscovered (Bluetoothgatt GATT, int status) {} When the connection can be read operation @Override public void ondescriptorread (Bluetoothgatt GATT, Bluetoothgattdescriptor descriptor, int status) { Span class= "Hljs-keyword" >super.ondescriptorread (GATT, descriptor, status); } ......};
? The process of the connection we connect through the service, or we can operate in the activity. OK, so far, the entire process of a BLE Bluetooth connected device has been clearly completed.
android4.x Bluetooth is not very mature
? But in the actual operation of the process will inevitably appear some more deceptive problems. For example, I use an address for Bluetooth device connection, occasionally there will be Bluetooth connection is not connected to the device after the connection does not return data and so on. At this point we may restart Bluetooth or mobile phone will be successful immediately. At this time we must not deceive, do not doubt their own life. This is because the android4.x Bluetooth is still not very mature. It can now be a test phase.
- Your phone may not be able to search for Bluetooth devices
- Sometimes you don't receive data on the radio.
- An exception is required to restart the phone or reboot to return to normal
What shall we do at this time?
Do not complain at this time, difficult to us as an Android programmer is doomed to such a bitter force?
The answer is in the negative.
How to optimize it? Then we should do it from the UI interface, the user experience.
-
Do a timer, if in determining the Bluetooth device is open and existing condition, you can not search for Bluetooth device in mobile phone search 5s to restart Bluetooth, and in the broadcast received Bluetooth turned on after the search again
-
User-appropriate prompts can be made on the UI
- When Bluetooth is on, prompt the user to go to the opener Bluetooth
- When Bluetooth is turned on, after it is on, the user is prompted to turn on the Bluetooth ...
- Bluetooth is turned on, the device is not connected, prompting the user to connect
- The device is connected on the phone, prompting the user, is connecting, please wait ...
- Bluetooth device connected on the phone, is reading, the prompt data is being read ...
We can't do anything on the Android system, we do what we can on the experience.
Mobile Bluetooth connection ble device requirements
- Mobile Android 4.3 + system sdk>=18
- Bluetooth version >=4.0
Learn the reference road Demo:https://github.com/androidstarjack/bluetooth_4.3-master
Learn here, about androidble bluetooth connection we have basically implemented Bluetooth search, connect, read and so on.
Everyone in the project if often involved in hardware such as hand ring, thermometer, sweat meter, ECG, blood pressure, etc. these ble Bluetooth devices, will definitely use the blue-related knowledge. Here the author first for everyone to step on the pit, a summary, for the back of the small partners in the study of Bluetooth as far as possible to step a few pits. If you do not have a clear understanding of the process of Bluetooth, please refer to the basics of Android Bluetooth bluetooth4.0--for more information.
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 the Android Bluetooth bluetooth--"Advanced article"