Android Low power Bluetooth-mobile phone as peripheral device

Source: Internet
Author: User

Overview

Since Android 5.0, Google has added support for Android phones as a low-power Bluetooth peripheral, the service side. Enables mobile phones to communicate with each other through low-power Bluetooth.

Development steps

In fact, this function only needs to be divided into setting up the broadcast and setting up a server two parts to complete

Setting up the server

The main operation of this step is bluetoothgattserver.

1. Define a Bluetoothgattservercallback callback as follows

Private Bluetoothgattservercallback Bluetoothgattservercallback =New Bluetoothgattservercallback () {@OverridePublicvoidOnconnectionstatechange (Bluetoothdevice device,int status,int newstate) {LOG.V ("Onconnectionstatechange","Connection status change"); }@OverridePublicvoidOnserviceadded (int status, Bluetoothgattservice service) {LOG.V ("Onserviceadded","Add service successfully"); }@OverridePublicvoidOncharacteristicreadrequest (Bluetoothdevice device,int RequestID,int offset, bluetoothgattcharacteristic characteristic) {LOG.V ("Characteristicreadreq","Remote device requests read data"); Bluetoothgattserver.sendresponse (device, RequestID, bluetoothgatt.gatt_success, offset,Newbyte[]{1,2,3,4,5,6,7,8,9,0}); }@OverridePublicvoidOncharacteristicwriterequest (Bluetoothdevice device,int RequestID, bluetoothgattcharacteristic characteristic,Boolean Preparedwrite,Boolean responseneeded,int offset,Byte[] value) {LOG.V ("Characteristicwritereq","Remote device request write data"); Bluetoothgattserver.sendresponse (device, RequestID, bluetoothgatt.gatt_success, offset,Newbyte[]{0,9,8,7,6,5,4,3,2,1});@OverridePublicvoidOndescriptorreadrequest (Bluetoothdevice device,int RequestID,int offset, Bluetoothgattdescriptor descriptor) {LOG.V ("Descriptorreadreq","Remote Device Request write descriptor"); Bluetoothgattserver.sendresponse (device, RequestID, bluetoothgatt.gatt_success, offset,Newbyte[]{10,11,12,13,14,15,16,17,18,19}); }@OverridePublicvoidOndescriptorwriterequest (Bluetoothdevice device,int RequestID, Bluetoothgattdescriptor descriptor,Boolean Preparedwrite,Boolean responseneeded,int offset,Byte[] value) {LOG.V ("Descriptorreadreq","Remote Device Request write descriptor"); Bluetoothgattserver.sendresponse (device, RequestID, bluetoothgatt.gatt_success, offset,Newbyte[]{19,18,17,16,15,14,13,12,11,10}); }@OverridePublicvoidonexecutewrite (bluetoothdevice device, int requestId, boolean execute) {log.v ( "Onexecutewrite",  "perform a pending write operation"); }  @Override public void onnotificationsent (bluetoothdevice device, int status) {LOG.V ( "Onnotificationsent",  "notification send"); }  @Override public void onmtuchanged (bluetoothdevice device, int MTU) {LOG.V (" onmtuchanged ", " MTU Change "); } }; 
    1. Bluetoothgattserver instances are obtained using the Bluetoothmanager Opengattserver (Context,bluetoothservercallback) method.
BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);bluetoothGattServer = mBluetoothManager.openGattServer(this, bluetoothGattServerCallback);

3. Add the appropriate service,characteristic and descriptor for the device (not required, but will usually be used). Here is just one example.

new BluetoothGattCharacteristic(CHARACTERISTIC_UUID,por,per);        BluetoothGattService service= new BluetoothGattService(SERVICE_UUID,pri);        service.addCharacteristic(characteristic);        bluetoothGattServer.addService(service);

Among them, Por,per,pri are:

private int por = BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristic.PROPERTY_INDICATE | BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE;    private int per = BluetoothGattCharacteristic.PERMISSION_READ | BluetoothGattCharacteristic.PERMISSION_WRITE;    private int pri = BluetoothGattService.SERVICE_TYPE_PRIMARY;

Can be adjusted according to their own needs.
This completes the simple setup of the Bluetoothgattserver.

Set up a broadcast

Here the main operation Bluetoothleadvertiser.

1. Use Bluetoothmanager to obtain bluetoothadapter, and then through Bluetoothadapter getbluetoothleadvertiser () method to get an instance of Bluetoothleadvertiser.

BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);        mBluetoothAdapter = mBluetoothManager.getAdapter();        mBluetoothLeAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();
    1. Turn on the radio

      Here are three things to prepare, advertisesettings,advertisedata and Advertisecallback.
      • Advertisesettings
        A broadcast configuration instance, obtained through Advertisesettings.builder.

        Advertisesettings.builder has four methods for setting parameters.
        respectively is
setAdvertiseMode(int advertiseMode)设置广播的模式,低功耗,平衡和低延迟三种模式;setConnectable(boolean connectable)设置是否可以连接。setTimeout(int timeoutMillis)设置广播的最长时间setTxPowerLevel(int txPowerLevel)设置广播的信号强度

Can be set according to the needs of their own, if not set according to the default parameters set.
Only a small example is provided here.

AdvertiseSettings settings = new AdvertiseSettings.Builder()                .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)                .setTimeout(0) .setConnectable(true) .build();
    • Advertisedata
      Examples of broadcast content, obtained through Advertisedata.builder

      contains several member functions.
addmanufacturerdata (int Manufacturerid, byte[] manufacturerSpecificData) Add vendor information, It doesn't seem to work. addserviceuuid (ParcelUuid Serviceuuid), addservicedata ( Span class= "hljs-variable" >parceluuid servicedatauuid, byte[] Servicedata" to add services to the broadcast, that is, to broadcast the services owned by the device. setincludedevicename (Boolean include devicename) whether the device name is broadcast. setincludetxpowerlevel (Boolean include txpowerlevel) broadcast signal strength          

A simple example is provided here.

AdvertiseData advertiseData = new AdvertiseData.Builder()                .setIncludeDeviceName(true)                .setIncludeTxPowerLevel(true)                .addServiceUuid(new ParcelUuid(SERVICE_UUID))                .build();
    • Advertisecallback
      Broadcast success or failure callbacks are relatively straightforward.
private Advertisecallback madvertisecallback = new Advertisecallback () { @Override public void  Onstartsuccess (advertisesettings settingsineffect) {log.v ( "start",  @Override public void onstartfailure (int errorCode) {log.v (

Finally through Bluetoothleadvertise's startadvertising (advertisesettings settings, Advertisedata advertisedata, Advertisecallback callback) turn on the radio
3. Turn off the broadcast
Closed by Bluetoothleadvertise stopadvertising (Advertisecallback callback).

Reference Link: https://developer.android.google.cn/reference/android/bluetooth/le/BluetoothLeAdvertiser.html
Code resource: http://download.csdn.net/detail/will4906/9777135

Android Low power Bluetooth-mobile phone as peripheral device

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.