Android improves Android phone and ble terminal communication _android

Source: Internet
Author: User
Tags bitwise operators uuid

Recently, wearing equipment has developed very fast, and the related technology is also flourishing, one of which is ble (Bluetooth low energy). BLE is the core profile of Bluetooth 4.0, the main function is fast search, fast connection, ultra-low power to maintain connectivity and transmission of data, weak data transmission rate is low, due to ble low power characteristics, it is widely used in wearable equipment. Android 4.3 only began to support the BLE API, so please sir this code in the Bluetooth 4.0 and Android 4.3 and above the system, in addition to the use of the BLE terminal is a Bluetooth 4.0 serial Bluetooth module.

Note: The author's i9100 Brush 4.4 system, unexpectedly also can communicate with BLE bluetooth module.

The BLE is divided into three parts, the service, the characteristic, and the descriptor, all of which are represented as unique identifiers by the UUID. A Bluetooth 4.0 terminal can contain multiple service, a service can contain multiple characteristic, a characteristic contains a value and multiple descriptor, and a descriptor contains a value. Generally speaking, characteristic is the key to exchanging data between mobile phone and ble terminal, characteristic has more fields related to permission, such as permission and property, and the most commonly used is property, The BLE bluetooth module used in this paper has no standard characteristic permission. The characteristic property can set read-write properties by using a combination of bitwise operators, such as read| WRITE, read| write_no_response| NOTIFY, so the property will be decomposed into the combination used (this decomposition method is included in the code).

This code from the Android 4.3 sample bluetoothlegatt, remove redundant code, get BLE device information through log, there are some necessary to read and write Bluetooth method, should be simplified to everyone can understand. This article full code can click here to download this site.

Next post the results of this article, the first is connected to the BLE equipment, all the equipment service, characteristic, descriptor, andmobile phone will write to characteristic uuid=0000ffe1-0000-1000-8000-00805f9b34fb "send data->" string, ble terminal received data via serial transmission to PC serial 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:00002A00-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:00002A01-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:00002A02-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:00002A03-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:00002A04-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:00001801-0000-1000-8000-00805F9B34FB
04-21 18:28:25.480:e/devicescanactivity (12254):---->char UUID:00002A05-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:00002902-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:0000FFE0-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| notify|
04-21 18:28:25.490:e/devicescanactivity (12254):-------->desc UUID:00002902-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:00002901-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 Scarlet Letter is bluetoothgattcallback by the Oncharacteristicread () callback and the log is played

The following log is a serial tool on the PC sent over the BLE module, and the log is played by Bluetoothgattcallback's oncharacteristicchanged ()
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, post the core code of this article:

public class Devicescanactivity extends Listactivity {private final static String TAG = DeviceScanActivity.class.getSim
 Plename ();

  Private final static String Uuid_key_data = "0000FFE1-0000-1000-8000-00805F9B34FB";
  Private Ledevicelistadapter Mledevicelistadapter;
  /** Search BLE terminal * * Private bluetoothadapter mbluetoothadapter;
  /** read-write ble terminal * * Private bluetoothleclass mble;
  Private Boolean mscanning;

  Private Handler Mhandler;
  Stops scanning after 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 are supported on the device.
    Then 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 (); }//Initializes a Bluetooth adapter.
    For APIs level and above, get a reference to//Bluetoothadapter through Bluetoothmanager.
    Final Bluetoothmanager Bluetoothmanager = (bluetoothmanager) getsystemservice (Context.bluetooth_service);
    Mbluetoothadapter = Bluetoothmanager.getadapter ();
    Checks if Bluetooth is supported on the device. if (Mbluetoothadapter = null) {Toast.maketext (this, r.string.error_bluetooth_not_supported, toast.length_short). Sh
      ow ();
      Finish ();
    Return
    //Open Bluetooth mbluetoothadapter.enable ();
    mble = new Bluetoothleclass (this);
      if (!mble.initialize ()) {LOG.E (TAG, "Unable to initialize Bluetooth");
    Finish ();
    ///Discover BLE Terminal Service when callback Mble.setonservicediscoverlistener (Monservicediscover);
  An event Mble.setondataavailablelistener (mondataavailable) that receives BLE terminal data interaction;

    } @Override protected void Onresume () {super.onresume (); InitIalizes List View adapter.
    Mledevicelistadapter = new Ledevicelistadapter (this);
    Setlistadapter (Mledevicelistadapter);
  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 bluetoothdevice Devi
    Ce = mledevicelistadapter.getdevice (position);
    if (device = null) return;
      if (mscanning) {Mbluetoothadapter.stoplescan (mlescancallback);
    Mscanning = false;
  } mble.connect (Device.getaddress ()); } private void Scanledevice (final Boolean enable) {if (enable) {//Stops scanning after a pre-defined scan p
      Eriod.
          Mhandler.postdelayed (New Runnable () {@Override public void run () {mscanning = false; MbluetoothadApter.stoplescan (Mlescancallback);
        Invalidateoptionsmenu ();
      }}, Scan_period);
      Mscanning = true;
    Mbluetoothadapter.startlescan (Mlescancallback);
      else {mscanning = false;
    Mbluetoothadapter.stoplescan (Mlescancallback);
  } invalidateoptionsmenu (); /** * Search to BLE Terminal Services event/private Bluetoothleclass.onservicediscoverlistener monservicediscover = new Onservicedi Scoverlistener () {@Override public void Onservicediscover (Bluetoothgatt GATT) {displaygattservices (mble.getsupported
 Gattservices ());
  }
  }; /** * received ble terminal data interaction Event/private Bluetoothleclass.ondataavailablelistener mondataavailable = new Ondataavailablelis Tener () {/** * ble terminal data Read event */@Override public void Oncharacteristicread (Bluetoothgatt GATT, Bluetoothgattch aracteristic characteristic, int status) {if (status = = Bluetoothgatt.gatt_success) log.e (TAG, "Oncharread" +gatt.get Device (). GetName () + "read" +characteristic.getUuid (). toString () + "->" +utils.bytestohexstring (Characteristic.getvalue ())); /** * received ble terminal write data callback/@Override public void Oncharacteristicwrite (Bluetoothgatt GATT, Bluetoothgattcharact Eristic characteristic) {log.e (TAG, "Oncharwrite" +gatt.getdevice (). GetName () + "write" +characteristic.getuuid ()
 . toString () + "->" +new String (Characteristic.getvalue ()));
  }
  };
  Device Scan callback.
    Private Bluetoothadapter.lescancallback Mlescancallback = new Bluetoothadapter.lescancallback () {@Override
        public void Onlescan (final bluetoothdevice device, int rssi, byte[] scanrecord) {runonuithread (new Runnable () {
          @Override public void Run () {mledevicelistadapter.adddevice (device);
        Mledevicelistadapter.notifydatasetchanged ();
    }
      });
  }
  };
    private void Displaygattservices (list<bluetoothgattservice> gattservices) {if (gattservices = = null) return; for (BluetoOthgattservice 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 ()); -----characteristics Field Information-----//list<bluetoothgattcharacteristic> Gattcharacteristics =
      Gattservice.getcharacteristics (); For (final bluetoothgattcharacteristic gattcharacteristic:gattcharacteristics) {log.e (TAG, "---->char uuid:" +g
        Attcharacteristic.getuuid ());
        int permission = Gattcharacteristic.getpermissions ();
        LOG.E (TAG, "---->char permission:" +utils.getcharpermission (permission));
        int property = Gattcharacteristic.getproperties ();
        LOG.E (TAG, "---->char property:" +utils.getcharpropertie);
     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)) that can communicate with the Bluetooth module The test reads the current characteristic data and triggers the Mondataavailable.oncharacteristicread () mhandler.postdelayed (New Runnable ()
            {@Override public void run () {mble.readcharacteristic (gattcharacteristic);
      }, 500);
      Accept characteristic written notification, receive the Bluetooth module data will trigger the Mondataavailable.oncharacteristicwrite ()
      Mble.setcharacteristicnotification (gattcharacteristic, true);
      Set the data content Gattcharacteristic.setvalue ("Send data->");
     Writes data to the Bluetooth module mble.writecharacteristic (gattcharacteristic); ///-----Descriptors Field Information-----//list<bluetoothgattdescriptor> gattdescriptors = Gattcharacteristic.getdescri
  Ptors (); for (Bluetoothgattdescriptor gattdescriptor:gattdescriptors) {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));

 }
      }
      }
    }//
  }
}

Interested readers will be able to test the operation of the code, hoping to help you with the development of Android projects.

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.