Android BLE development-communication between Android mobile phones and BLE Terminals

Source: Internet
Author: User
Tags bitwise operators

This article from http://blog.csdn.net/hellogv/, reference must indicate the source!

Recently, wearable devices have become very popular and technologies have become increasingly popular. One of them is BLE (Bluetooth Low Energy ). BLE is the core Profile of Bluetooth 4.0. Its main function is fast search, fast connection, ultra-low power consumption, and data transmission. Its weakness is its low data transmission rate, therefore, it is widely used in wearable devices. Android 4.3 started to support the ble api. Therefore, we recommend that you run the code in Bluetooth 4.0, Android 4.3, and later versions, in addition, the BLE terminal used in this article is a Bluetooth 4.0 serial port bluetooth module.

PS: My i9100 can communicate with the BLE bluetooth module even after the 4.4 system is refreshed.


BLE is divided into three parts: Service, Characteristic, and Descriptor, which are all uniquely identified by UUID.A Bluetooth 4.0 Terminal can contain multiple services, and a Service can contain multipleCharacteristic,Characteristic contains one Value and multipleDescriptor,Descriptor contains a Value.In general, Characteristic is the key to data exchange between mobile phones and BLE terminals. Characteristic has many PERMISSION-related fields, such as PERMISSION and PROPERTY, and the most common one is PROPERTY, the BLE bluetooth module used in this article has no standard Characteristic PERMISSION. Characteristic properties can be set through bitwise operators, such as READ | WRITE, READ | WRITE_NO_RESPONSE | policy, therefore, after reading the PROPERTY, it should be decomposed into the used combination (this decomposition method is included in the Code in this article ).


The code in this article is changed from javasthlegatt In the Android 4.3 Sample. The redundant code is removed and the information of the BLE device obtained is logged. There are also some necessaryRead/write BluetoothIt should be simplified to everyone's understanding. The code in this article can be downloaded at http://download.csdn.net/detail/hellogv/7228819. Next, I will post the running results of this Article. First, after connecting to the BLE device, I will enumerate all the services, Characteristic, and Descriptor of the device, in addition, the mobile phone will write a "send data->" string to Characteristic uuid = effecffe1-0000-1000-8000-00805f9b34fb, And the BLE terminal will receive data transmitted to the PC serial assistant through the serial port (see PC serial port Assistant ):

04-21 18:28:25. 465: E/DeviceScanActivity (12254): --> service type: PRIMARY
04-21 18:28:25. 465: E/DeviceScanActivity (12254): --> includedServices size: 0
04-21 18:28:25. 465: E/DeviceScanActivity (12254): --> service uuid: 00001800-0000-1000-8000-00805f9b34fb
04-21 18:28:25. 465: E/DeviceScanActivity (12254): ----> char uuid: 1272a00-0000-1000-8000-00805f9b34fb
04-21 18:28:25. 465: E/DeviceScanActivity (12254): ----> char permission: UNKNOW
04-21 18:28:25. 465: E/DeviceScanActivity (12254): ----> char property: READ
04-21 18:28:25. 465: E/DeviceScanActivity (12254): ----> char uuid: 1272a01-0000-1000-8000-00805f9b34fb
04-21 18:28:25. 470: E/DeviceScanActivity (12254): ----> char permission: UNKNOW
04-21 18:28:25. 470: E/DeviceScanActivity (12254): ----> char property: READ
04-21 18:28:25. 470: E/DeviceScanActivity (12254): ----> char uuid: 1272a02-0000-1000-8000-00805f9b34fb
04-21 18:28:25. 470: E/DeviceScanActivity (12254): ----> char permission: UNKNOW
04-21 18:28:25. 470: E/DeviceScanActivity (12254): ----> char property: READ | WRITE |
04-21 18:28:25. 470: E/DeviceScanActivity (12254): ----> char uuid: 1272a03-0000-1000-8000-00805f9b34fb
04-21 18:28:25. 470: E/DeviceScanActivity (12254): ----> char permission: UNKNOW
04-21 18:28:25. 475: E/DeviceScanActivity (12254): ----> char property: READ | WRITE |
04-21 18:28:25. 475: E/DeviceScanActivity (12254): ----> char uuid: 1272a04-0000-1000-8000-00805f9b34fb
04-21 18:28:25. 475: E/DeviceScanActivity (12254): ----> char permission: UNKNOW
04-21 18:28:25. 475: E/DeviceScanActivity (12254): ----> char property: READ
04-21 18:28:25. 475: E/DeviceScanActivity (12254): --> service type: PRIMARY
04-21 18:28:25. 475: E/DeviceScanActivity (12254): --> includedServices size: 0
04-21 18:28:25. 475: E/DeviceScanActivity (12254): --> service uuid: 1091801-0000-1000-8000-00805f9b34fb
04-21 18:28:25. 480: E/DeviceScanActivity (12254): ----> char uuid: 1272a05-0000-1000-8000-00805f9b34fb
04-21 18:28:25. 480: E/DeviceScanActivity (12254): ----> char permission: UNKNOW
04-21 18:28:25. 480: E/DeviceScanActivity (12254): ----> char property: INDICATE
04-21 18:28:25. 480: E/DeviceScanActivity (12254): --------> desc uuid: 20172902-0000-1000-8000-00805f9b34fb
04-21 18:28:25. 480: E/DeviceScanActivity (12254): --------> desc permission: UNKNOW
04-21 18:28:25. 480: E/DeviceScanActivity (12254): --> service type: PRIMARY
04-21 18:28:25. 480: E/DeviceScanActivity (12254): --> includedServices size: 0
04-21 18:28:25. 480: E/DeviceScanActivity (12254): --> service uuid: effecffe0-0000-1000-8000-00805f9b34fb
04-21 18:28:25. 480: E/DeviceScanActivity (12254): ----> char uuid: 0000ffe1-0000-1000-8000-00805f9b34fb
04-21 18:28:25. 480: E/DeviceScanActivity (12254): ----> char permission: UNKNOW
04-21 18:28:25. 480: E/DeviceScanActivity (12254): ----> char property: READ | WRITE_NO_RESPONSE | policy |
04-21 18:28:25. 490: E/DeviceScanActivity (12254): --------> desc uuid: 20172902-0000-1000-8000-00805f9b34fb
04-21 18:28:25. 490: E/DeviceScanActivity (12254): --------> desc permission: UNKNOW
04-21 18:28:25. 490: E/DeviceScanActivity (12254): --------> desc uuid: 20172901-0000-1000-8000-00805f9b34fb
04-21 18:28:25. 490: E/DeviceScanActivity (12254): --------> desc permission: UNKNOW
04-21 18:28:26. 025: E/DeviceScanActivity (12254): onCharRead ble device read 0000ffe1-0000-1000-8000-00805f9b34fb-> 00

Here, the red letter is played by the onCharacteristicRead () callback of BluetoothGattCallback and




The following logs are sent by the serial port tool on the PC through the BLE module. logs are output by onCharacteristicChanged () of ipvthgattcallback.
04-21 18:30:18. 260: E/DeviceScanActivity (12254): onCharWrite ble device write 0000ffe1-0000-1000-8000-00805f9b34fb-> send data to phone
04-21 18:30:18. 745: E/DeviceScanActivity (12254): onCharWrite ble device write 0000ffe1-0000-1000-8000-00805f9b34fb-> send data to phone
04-21 18:30:19. 085: E/DeviceScanActivity (12254): onCharWrite ble device write 0000ffe1-0000-1000-8000-00805f9b34fb-> send data to phone
04-21 18:30:19. 350: E/DeviceScanActivity (12254): onCharWrite ble device write 0000ffe1-0000-1000-8000-00805f9b34fb-> send data to phone
04-21 18:30:19. 605: E/DeviceScanActivity (12254): onCharWrite ble device write 0000ffe1-0000-1000-8000-00805f9b34fb-> send data to phone
04-21 18:30:19. 835: E/DeviceScanActivity (12254): onCharWrite ble device write 0000ffe1-0000-1000-8000-00805f9b34fb-> send data to phone
04-21 18:30:20. 055: E/DeviceScanActivity (12254): onCharWrite ble device write 0000ffe1-0000-1000-8000-00805f9b34fb-> send data to phone
04-21 18:30:20. 320: E/DeviceScanActivity (12254): onCharWrite ble device write 0000ffe1-0000-1000-8000-00805f9b34fb-> send data to phone
04-21 18:30:20. 510: E/DeviceScanActivity (12254): onCharWrite ble device write 0000ffe1-0000-1000-8000-00805f9b34fb-> send data to phone
04-21 18:30:20. 735: E/DeviceScanActivity (12254): onCharWrite ble device write 0000ffe1-0000-1000-8000-00805f9b34fb-> send data to phone
04-21 18:30:21. 000: E/DeviceScanActivity (12254): onCharWrite ble device write 0000ffe1-0000-1000-8000-00805f9b34fb-> send data to phone

Next we will post the core code of this article:

Public class DeviceScanActivity extends ListActivity {private final static String TAG = DeviceScanActivity. class. getSimpleName (); private final static String UUID_KEY_DATA = "success"; private LeDeviceListAdapter mLeDeviceListAdapter;/** search for BLE Terminal */private javasthadapter mbluw.thadapter; /** read/write BLE Terminal */private javasthleclass mBLE; private boolean mScanning; private Ha Ndler mHandler; // Stops scanning after 10 seconds. private static final long SCAN_PERIOD = 10000; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); getActionBar (). setTitle (R. string. title_devices); mHandler = new Handler (); // Use this check to determine whether BLE is supported on the device. then you can // selectively disable BLE-related features. I F (! GetPackageManager (). hasSystemFeature (PackageManager. feature_effecth_le) {Toast. makeText (this, R. string. ble_not_supported, Toast. LENGTH_SHORT ). show (); finish ();} // Initializes a Bluetooth adapter. for API level 18 and above, get a reference to // descrithadapter through descrithmanager. final effecthmanager implements thmanager = (effecthmanager) getSystemService (Context. BLUETOOTH_SERVICE ); Mblustmthadapter = effecthmanager. getAdapter (); // Checks if Bluetooth is supported on the device. if (mblustmthadapter = null) {Toast. makeText (this, R. string. error_effecth_not_supported, Toast. LENGTH_SHORT ). show (); finish (); return;} // enable Bluetooth mblustmthadapter. enable (); mBLE = new incluthleclass (this); if (! MBLE. initialize () {Log. e (TAG, "Unable to initialize Bluetooth"); finish () ;}// callback mBLE when the BLE Terminal Service is found. setOnServiceDiscoverListener (mOnServiceDiscover); // receives the event mBLE for the BLE terminal data interaction. setOnDataAvailableListener (mOnDataAvailable) ;}@ Override protected void onResume () {super. onResume (); // Initializes list view adapter. mLeDeviceListAdapter = new LeDeviceListAdapter (this); setListAdapter (mLeDeviceListAdap Ter); scanLeDevice (true) ;}@ Override protected void onPause () {super. onPause (); scanLeDevice (false); mLeDeviceListAdapter. clear (); mBLE. disconnect () ;}@ Override protected void onStop () {super. onStop (); mBLE. close () ;}@ Override protected void onListItemClick (ListView l, View v, int position, long id) {final incluthdevice device = mLeDeviceListAdapter. getDevice (position); if (device = null) Return; if (mScanning) {mbluw.thadapter. stopLeScan (mLeScanCallback); mScanning = false;} mBLE. connect (device. getAddress ();} private void scanLeDevice (final boolean enable) {if (enable) {// Stops scanning after a pre-defined scan period. mHandler. postDelayed (new Runnable () {@ Override public void run () {mScanning = false; mbluw.thadapter. stopLeScan (mLeScanCallback); invalidateOptionsMen U () ;}}, SCAN_PERIOD); mScanning = true; mbluw.thadapter. startLeScan (mLeScanCallback);} else {mScanning = false; mbluw.thadapter. stopLeScan (mLeScanCallback);} invalidateOptionsMenu ();}/*** events of BLE Terminal Service searched */private incluthleclass. onServiceDiscoverListener mOnServiceDiscover = new OnServiceDiscoverListener () {@ Overridepublic void onServiceDiscover (descrithgatt gatt) {displayGattServices (MBLE. getSupportedGattServices () ;};/*** receives the event of BLE Terminal Data Interaction */private BluetoothLeClass. mOnDataAvailable = new events () {/*** BLE terminal data read events */@ Overridepublic void onCharacteristicRead (descrithgatt gatt, descrithgattcharacteristic characteristic, int status) {if (status = processing thgatt. GATT_SUCCESS) Log. e (TAG, "onCharRead" + gatt. getDevice (). getName () + "read "+ Characteristic. getUuid (). toString () + "->" + Utils. bytesToHexString (characteristic. getValue ();}/*** receives the data write callback from the BLE Terminal */@ Overridepublic void onCharacteristicWrite (descrithgatt gatt, descrithgattcharacteristic characteristic) {Log. e (TAG, "onCharWrite" + gatt. getDevice (). getName () + "write" + characteristic. getUuid (). toString () + "->" + new String (characteristic. getValue () ;}}; // Device scan callback. Private transferthadapter. leScanCallback mLeScanCallback = new systthadapter. leScanCallback () {@ Override public void onLeScan (final effecthdevice device, int Arg, byte [] scanRecord) {runOnUiThread (new Runnable () {@ Override public void run () {mLeDeviceListAdapter. addDevice (device); mLeDeviceListAdapter. notifyDataSetChanged () ;}}) ;}; private void displayGattServices (List <BluetoothGatt Service> gattServices) {if (gattServices = null) return; for (gatethgattservice gattService: gattServices) {// ----- Service field information ----- // int type = gattService. getType (); Log. e (TAG, "--> service type:" + Utils. getServiceType (type); Log. e (TAG, "--> includedServices size:" + gattService. getIncludedServices (). size (); Log. e (TAG, "--> service uuid:" + gattService. getUuid (); // ----- field information of Characteristics ----- // List <symbol thgattcharacteristic> gattCharacteristics = gattService. getCharacteristics (); for (final character thgattcharacteristic gattCharacteristic: gattCharacteristics) {Log. e (TAG, "----> char uuid:" + gattCharacteristic. getUuid (); int permission = gattCharacteristic. getPermissions (); Log. e (TAG, "----> char permission:" + Utils. getCharPermission (permission); int property = gattCharacteristic. getProp Erties (); Log. e (TAG, "----> char property:" + Utils. getCharPropertie (property); byte [] data = gattCharacteristic. getValue (); if (data! = Null & data. length> 0) {Log. e (TAG, "----> char value:" + new String (data);} // UUID_KEY_DATA is a Characteristic if (gattCharacteristic. getUuid (). toString (). equals (UUID_KEY_DATA) {// test to read the current Characteristic data. mOnDataAvailable is triggered. onCharacteristicRead () mHandler. postDelayed (new Runnable () {@ Override public void run () {mBLE. readCharacteristic (gattCharacteristic); }}, 500); // accepts Characteristic written MOnDataAvailable will be triggered after receiving the data from the bluetooth module. onCharacteristicWrite () mBLE. setCharacteristicNotification (gattCharacteristic, true); // set the data content gattCharacteristic. setValue ("send data->"); // write data into the bluetooth module mBLE. writeCharacteristic (gattCharacteristic);} // ----- Descriptors field information ----- // List <symbol thgattdescriptor> gattDescriptors = gattCharacteristic. getDescriptors (); for (descrithgattdescriptor gattDescriptor: gattDes Criptors) {Log. e (TAG, "--------> desc uuid:" + gattDescriptor. getUuid (); int descPermission = gattDescriptor. getPermissions (); Log. e (TAG, "--------> desc permission:" + Utils. getDescPermission (descPermission); byte [] desData = gattDescriptor. getValue (); if (desData! = Null & desData. length> 0) {Log. e (TAG, "--------> desc value:" + new String (desData ));}}}}//}}

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.