Android Bluetooth 4.0 BLE

Source: Internet
Author: User

Android ble bluetooth 4.0, which means that the API level >= 18, and Bluetooth 4.0-enabled mobile phones can be used.

BLE is the core profile of Bluetooth 4.0, the main feature is fast search, fast connection, ultra-low power to maintain connectivity and transmission of data, the vulnerability is low data transmission rate, due to the low power consumption of ble, it is widely used in wearable devices.

Official demo:http://developer.android.com/guide/topics/connectivity/bluetooth-le.html

Official demo (CSDN download, thank you for sharing): http://download.csdn.net/detail/lqw770737185/8116019

because the search needs to minimize power consumption, you need to be aware of the actual use:1. When the corresponding device is found, stop scanning immediately, 2, do not loop search device, set the appropriate time limit for each search. Avoid constant scanning and power consumption when the device is not in the available range. Note: Add Permissions:<uses-permission android:name= "Android.permission.BLUETOOTH"/>
<uses-permission android:name= "Android.permission.BLUETOOTH_ADMIN"/> In addition to Bluetooth permissions, if required ble Feature also needs to declare uses-feature:<uses-feature android:name= "Android.hardware.bluetooth_le" android:required= "true"/ >when required is set to true, the app can only be installed on an Android device that supports BLE, and when required is false, the Android device runs properly and needs to determine if the device supports BLE feature when the code is running:
if (! Getpackagemanager (). Hassystemfeature (Packagemanager.feature_bluetooth_le)) {      // does not support ble     finish ();}
(1) Implement the BluetoothAdapter.LeScanCallback interface, the BLE device search results will be returned through this callback
1     //Device Scan callback.2     PrivateBluetoothadapter.lescancallback Mlescancallback =3             NewBluetoothadapter.lescancallback () {4 6 @Override7          Public voidOnlescan (FinalBluetoothdevice device,intRssibyte[] scanrecord) {8              -         } to  +};

(2) Turn off search for BLE devices

1 mbluetoothadapter.stoplescan (mlescancallback);

(3) Turn on BLE device search

1 mbluetoothadapter.startlescan (mlescancallback);

Note: When searching, you can only search for traditional Bluetooth devices or BLE devices, which are completely independent and not searchable at the same time.

(4) Use Bluetoothgatt to connect the device

The two devices communicate via BLE, and the GATT connection needs to be established first. Here we are talking about the Android device as the client side, connected to the GATT Server. To connect to the GATT Server, you need to call Bluetoothdevice's Connectgatt () method. This function takes three parameters: Context, AutoConnect (Boolean), and Bluetoothgattcallback object.
1 Private Bluetoothgatt Mbluetoothgatt;
  1  final  bluetoothdevice device =< Span style= "color: #000000;" > Mbluetoothadapter  .getremotedevice (address);   if  (device = = null  ) {  LOG.W (TAG," Device not F  Ound. Unable to connect. "   return  false    "   6  Mbluetoothgatt = Device.connectgatt (this , true , mgattcallback); 

(5) Use Bluetoothgattcallback to communicate with the device

1 PrivateBluetoothgattcallback Mgattcallback =NewBluetoothgattcallback () {2 @Override3      Public voidOnconnectionstatechange (Bluetoothgatt GATT,4         intStatusintnewstate) {5         Super. Onconnectionstatechange (GATT, status, NewState);9         if(NewState = =bluetoothprofile.state_connected) {Ten setState (state.connected); One gatt.discoverservices (); A}Else { - setState (state.idle); -         } the     } -   - @Override -      Public voidonservicesdiscovered (Bluetoothgatt GATT, +          intstatus) { -         if(Status = =bluetoothgatt.gatt_success) { +LOG.V (TAG, "onservicesdiscovered:" +status); A         } at     } -}

The connection will go this way onconnectionstatechange, the new state passed over is the connection state, then in this method call this sentence: Mbluetoothgatt.discoverservices (),

Mbluetoothgatt is the object at the completion of the connection, remember, after invoking this sentence, the Onservicesdiscovered method of the callback function will go. In this method to get some service of the device, Bluetooth channel, and then through these channels to send data to the peripheral.

In a Bluetooth device, it contains multiple bluetoothgattservice, and each bluetoothgattservice contains multiple bluetoothgattcharacteristic.

(1) Access to the list of services in the device mbluetoothgatt.getservices (); Or get a service from a UUID:

 Public List<bluetoothgattservice> getsupportedgattservices () {        ifnull)             returnnull;         return mbluetoothgatt.getservices ();         // or to get a service mbluetoothgatt.getservices (UUID) through a UUID;}

(2) through the GATT this pair, is the Bluetooth connection is completed after the object acquired, through this object set the specified channel to the device to write and read data.

Service, the Get characteristic collection calls Gattservice.getcharacteristics ():

In characteristic, it is possible to pass mbluetoothgatt.readcharacteristic (characteristic); To read the data inside it, the result is obtained in the Mgattcallback callback function.

Write as data: characteristic. SetValue;

Mbluetoothgatt. wirtecharacteristic (mcurrentcharacteristic);

1  Public voidwirtecharacteristic (bluetoothgattcharacteristic characteristic) {2 3         if(Mbluetoothadapter = =NULL|| Mbluetoothgatt = =NULL) {4LOG.W (TAG, "Bluetoothadapter not initialized");5             return;6         }7 8 mbluetoothgatt.writecharacteristic (characteristic);9}
1  Public voidreadcharacteristic (bluetoothgattcharacteristic characteristic) {2         if(Mbluetoothadapter = =NULL|| Mbluetoothgatt = =NULL) {3LOG.W (TAG, "Bluetoothadapter not initialized");4             return;5         }6 mbluetoothgatt.readcharacteristic (characteristic);7}

Note: bluetoothgattcharacteristic this is the specified channel, Bluetooth service:

1 NULL ; 2 characteristic = Mgattcharacteristics.get (4). Get (4);

These two numbers are the services that you want to send data from the specified service.

If you want to make more than one connection, you can put the Bluetoothgatt object into a list after each connection is completed, and the obtained service will be placed in a list, and then the data will be sent to different GATT to send different channel data.

Reference:

Android boosts Android phone with BLE terminal communication

Android Bluetooth 4 multi-Channel

Android Bluetooth Low Energy (official)

Android Bluetooth 4.0 BLE

Related Article

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.