Use Blelib's easy fix Android low power Bluetooth BLE 4.0 development specific explanation

Source: Internet
Author: User

Reprint please indicate source: http://blog.csdn.net/kjunchen/article/details/50909410

use Blelib's easy fix Android low power Bluetooth BLE 4.0 development specific explanation
    • Demo Sample source code : Https://github.com/junkchen/BleLib/tree/master/sample
    • Android ble4.0 Development Basics : http://blog.csdn.net/kjunchen/article/details/50339549

Blelib is an auxiliary library developed for Android low power Bluetooth 4.0 and above. A line of code to resolve BLE initialization, scanning, connection, feature read and write, set notifications and other operations.

The blelib supports a single BLE connection or multiple BLE devices connected at the same time.

Key classes in the Blelib:

    • Bleservice is a service class for a single BLE connection operation
    • The Gattattributes class includes UUID values for the services and features specified by the Bluetooth alliance
    • Multiplebleservice class is a service class that can connect multiple Bluetooth devices at the same time
usageFirst step: Join Blelib Library Dependency

So. The Build.gradle file in your project module is added to the storage dependency. For example, the following:

{    compile ‘com.junkchen.blelib:blelib:1.0.4‘}

Just this one sentence can use Blelib library, convenient bar, want is this effect.
When using Android Studio, it is better to add dependencies in the following way, get the latest version number, and the result is the same as above, and enter the library dependency settings of the module. Search Blelib to get:

Step Two: Bind the Blelib service

The BLE service class in the Blelib library inherits service, so it is recommended that the binding services be used.

(assuming that the project needs to be connected more than the BLE device for control please bind Multiplebleservice)

PrivateBleservice Mbleservice;Private BooleanMisbind;PrivateServiceconnection serviceconnection =NewServiceconnection () {@Override     Public void onserviceconnected(componentname name, IBinder service) {Mbleservice = ((bleservice.localbinder) service). GetService ();if(Mbleservice.initialize ()) {if(Mbleservice.enablebluetooth (true) {Mbleservice.scanledevice (true); Toast.maketext (blescanactivity. This,"Bluetooth was opened", Toast.length_short). Show (); }        }Else{Toast.maketext (blescanactivity). This,"not support Bluetooth", Toast.length_short). Show (); }    }@Override     Public void onservicedisconnected(componentname name) {Mbleservice =NULL; Misbind =false; }};Private void Dobindservice() {Intent serviceintent =NewIntent ( This, Bleservice.class); Bindservice (Serviceintent, serviceconnection, context.bind_auto_create);}Private void Dounbindservice() {if(Misbind)       {Unbindservice (serviceconnection); Mbleservice =NULL; Misbind =false; }}
Step Three: Initialize the operation

When the service is bound, it can be initialized to infer whether Bluetooth is supported by the machine. Calls such as the following methods:

mBleService.initialize();//Ble初始化操作  

The method returns a Boolean value. A return of TRUE indicates success in initialization. Bluetooth is supported; return FALSE indicates that the initialization operation failed. None of the operations may be possible.

Fourth step: Turn on Bluetooth

When the initialization operation is successful, Bluetooth can be turned on, such as the following methods:

mBleService.enableBluetooth(boolean enable);//打开或关闭蓝牙 

This method is required to pass in a Boolean argument. True indicates Bluetooth is turned on, false to turn off Bluetooth, and returns a Boolean parameter, which returns true to turn Bluetooth on or off.

Fifth step: Scan the BLE device

When Bluetooth is turned on, the BLE device can be scanned, such as the following methods:

mBleService.scanLeDevice(booleanlong scanPeriod);//启动或停止扫描Ble设备  

Calling this method requires a Boolean argument, true to start scanning the BLE device, false to stop the scan, the default scan after 10 seconds to stop, assuming that you want to set the scan time, you can enter a long parameter, indicating the time unit is milliseconds, If 3000 means stop scanning after 3 seconds, the end of the scan will emit a broadcast.

The results of the scan can be obtained from either a scan listener or a broadcast receiver, such as the following:

listening mode receives the scan to the BLE device
//Ble扫描回调mBleService.setOnLeScanListener(new BleService.OnLeScanListener() {    @Override    publicvoidonLeScanintbyte[] scanRecord) {        //每当扫描到一个Ble设备时就会返回,(扫描结果反复的库中已处理)    

( note : Setting the listener must wait until the Bleservice service is bound, or it will cause a null pointer exception)

radio receive scan to BLE device
PrivateBroadcastreceiver Blereceiver= NewBroadcastreceiver () {@Override Public voidOnReceive (context context, Intent Intent) {if(Intent.Getaction ().equals(Bleservice.Action_bluetooth_device)) {StringTmpdevname=Intent.Getstringextra ("Name");StringTmpdevaddress=Intent.Getstringextra ("Address");Log.ITAG,"Name:" +Tmpdevname+ ", Address:" +tmpdevaddress); }Else if(Intent.Getaction ().equals(Bleservice.action_scan_finished)) {//scan ble device stop}       }   };

Both ways to get both. But the listening method gets more information. You can choose which way to use according to your own needs.

Sixth step: Connect to the BLE service

When the BLE device is scanned, it can be connected. Calls such as the following methods:

mBleService.connect(String address);//连接Ble  mBleService.disconnect();//取消连接  

The connection needs to pass in the address of the BLE device to be connected.

Connection status can be obtained either from the connection monitoring or the broadcast receiver. The Setup method is as follows:

Listen for ble connection status
//ble Connection CallbackMbleservice.setonconnectlistener (NewBleservice.onconnectlistener () {@Override     Public void OnConnect(Bluetoothgatt GATT,intStatusintNewState) {if(newstate = = bluetoothprofile.state_disconnected) {//ble connection is disconnected}Else if(newstate = = bluetoothprofile.state_connecting) {//ble is connecting}Else if(newstate = = bluetoothprofile.state_connected) {//ble is connected}Else if(newstate = = bluetoothprofile.state_disconnecting) {//ble is disconnecting}    }});
broadcast receive BLE connection status
privatenew BroadcastReceiver() {       @Override       publicvoidonReceive(Context context, Intent intent) {           if (intent.getAction().equals(BleService.ACTION_GATT_CONNECTED)) {               //Ble已连接           elseif (intent.getAction().equals(BleService.ACTION_GATT_DISCONNECTED)) {               //Ble连接已断开           }        }   };

The service is acquired when the BLE is connected. Assuming that the services and features cannot be found, then it is not possible to read and write the features and to set up GATT notifications.

Service discovery listener settings such as the following:

//Ble服务发现回调mBleService.setOnServicesDiscoveredListener(new BleService.OnServicesDiscoveredListener() {    @Override    publicvoidonServicesDiscoveredint status) {    }});
Seventh Step: Read and write BLE features and receive GATT notifications

When you connect to ble and get services, you are able to read and write features and set up GATT notifications. Actions such as the following:

mBleService.setCharacteristicNotification();//设置通知  mBleService.readCharacteristic();//读取数据  mBleService.writeCharacteristic();//写入数据 

The data that is read by the attribute and the GATT notification receive data Settings Ondataavailablelistener listen to get. Settings such as the following:

//Ble数据回调mBleService.setOnDataAvailableListener(new BleService.OnDataAvailableListener() {    @Override    publicvoidonCharacteristicReadint status) {        //处理特性读取返回的数据    }    @Override    publicvoidonCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {        //处理通知返回的数据    }});
Summary

The final little summary of the development steps for Android low-power bluetooth ble using the Blelib library:

    1. Join Blelib Library Dependency
    2. Binding Blelib Services
    3. Initialize operation
    4. Turn on bluetooth
    5. Scan ble devices
    6. Connect to the BLE service
    7. Read-write BLE feature and receive GATT notification
Author
    • Name: Junk Chen
    • Github: Https://github.com/junkchen
    • Blog: Http://blog.csdn.net/kjunchen
    • email: [email protected]
    • QQ Group : 365532949

2016/3/16 21:49:15

Use Blelib's easy fix Android low power Bluetooth BLE 4.0 development specific explanation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.