这段时间要定制一个蓝牙BLE设备的主机端APP,负责读写iBeacon等设备的蓝牙数据,计划用Java和Qt for Android实现两个简单的demo,比较后决定继续基于哪个开发,其中Qt 蓝牙模块以前使用过,在官方demo上做过一个蓝牙心率计的APP,现在考虑尝试使用Java 开发,谷歌在Android4.3开始提供的BLE API。

第一部分记录本人调试、分析谷歌官方demo:BluetoothLeGatt的源码要点。

第二部分总结Android BLE开发的七个主要步骤。


一、Android4.3官方BLE demo源码要点

1.官方源码共3个Activity和1个Service:
服务BluetoothService提供BLE标准API;
MainActivity仅作主菜单的显示,菜单栏里提供scan和stop两个按钮的功能;
扫描设备在DeviceScanActivity,扫描成功会将设备显示在一个简易的设备listview;
点击ListviewItem(某个设备)时会跳转到DeviceControlActivity,然后可以开始进行连接、数据交互操作。

2.APP和BLE设备交互的过程分析:
    点击设备后跳转到DeviceControlActivity,该活动主要通过BroadcastReceiver来判定操作:
    (1)首先会建立连接(BluetoothLeService.ACTION_GATT_CONNECTED。equals(action)条件触发),更新连接状态;
    (2)然后会刷新显示所有的services和characteristics(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)条件触发);
    (3)然后等待点击ExpandableListView的child(二级item:此处为某个service下的characteristic),即ExpandableListView.OnChildClickListener监听事件,
监听事件中开始进行数据的交互:根据characteristic的uuid来决定发送哪条数据,并设置哪些characteristics需要被写的通知(notification);
    (4)返回BroadcastReceiver,接收到BLE设备数据后会触发数据有效(BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)条件触发),显示BLE设备发来的数据。
    以上四步便完成一次数据发送和接收的交互过程。
     注:除了上述3种action,BroadcastReceiver里还有一种action就是断开连接(BluetoothLeService.ACTION_GATT_DISCONNECTED),条件触发则执行断开连接操作。

3.DeviceControlActivity补充代码:

二、Android BLE开发七步走

//退出时断开蓝牙连接
     @Override
     protected void onStop() {
         super.onStop();
         Toast.makeText(this,"BLE is closing...", Toast.LENGTH_SHORT).show();
         mBLE.close();
     }


1.解决BLE权限问题

在manifest中加入BLUETOOTH和BLUETOOTH_ADMIN权限:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>



如果想声明你的app只为具有BLE的设备提供,在manifest文件中包括:

<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>


但是如果想让你的app提供给那些不支持BLE的设备,需要在manifest中包括上面代码并设置required="false"


然后加入检查BLE是否被设备支持的代码:

// 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
            finish();
        }


2.设置BLE适配器

所有的蓝牙活动都需要蓝牙适配器。BluetoothAdapter代表设备本身的蓝牙适配器(蓝牙无线)。整个系统只有一个蓝牙适配器。

(1)获取BluetoothAdapter

// 初始化 Bluetooth adapter, 通过蓝牙管理器得到一个参考蓝牙适配器(API必须在以上android4.3或以上和版本)
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();



(2)检查是否打开蓝牙

// 蓝牙适配器获取失败
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }




3.扫描BLE设备

为了发现BLE设备,使用startLeScan())方法。这个方法需要一个参数BluetoothAdapter.LeScanCallback。

通过该回调函数返回扫描结果,因此必须自行实现。

/**
 * 扫描和显示可以提供的蓝牙设备.
 */
public class DeviceScanActivity extends ListActivity {
    private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning;
    private Handler mHandler;
    // 10秒后停止寻找.
    private static final long SCAN_PERIOD = 10000;
    ...
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // 经过预定扫描期后停止扫描
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);
            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        ...
    }
...
}

若只想扫描指定类型的外围设备,可以改为调用startLeScan(UUID[], BluetoothAdapter.LeScanCallback)),需要提供你的app支持的GATT services的UUID对象数组。

注意:只能扫描BLE设备或传统蓝牙设备,不能同时扫描BLE和传统蓝牙设备。

作为BLE扫描结果的接口,下面是BluetoothAdapter.LeScanCallback的实现。

private LeDeviceListAdapter mLeDeviceListAdapter;
...
// 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();
           }
       });
   }
};

4.连接到BLE设备服务

与BLE设备交互的第一步是连接,需要调用connectGATT()方法,三个参数:

参1:context对象;参2:自动连接(boolean);参3:BluetoothGattCallback


mBluetoothGatt = device.connectGatt(this, false, mGattCallback);


BluetoothGattCallback用于传递给用户,如连接状态以及任何进一步GATT客户端的操作。官方demo是在其BluetoothService的服务代码中实现了不同类型的回调方法,当一个回调被触发时,会调用相应的broadcastUpdate()方法并传递一个action.

然后返回到DeviceControlActivity(官方demo中处理连接事件的Activity),这个回调事件由BroadcastReceiver处理,判断以下四种情况:

ACTION_GATT_CONNECTED:连接到服务端

ACTION_GATT_DISCONNECTED:未连接到服务端

ACTION_GATT_SERVICES_DISCOVERED:发现服务

ACTION_DATA_AVAILABLE:接收到数据

官方处理代码如下:

//通过BLE API服务端与BLE设备交互
public class BluetoothLeService extends Service {
    private final static String TAG = BluetoothLeService.class.getSimpleName();
    private BluetoothManager mBluetoothManager; //蓝牙管理器
    private BluetoothAdapter mBluetoothAdapter; //蓝牙适配器
    private String mBluetoothDeviceAddress; //蓝牙设备地址
    private BluetoothGatt mBluetoothGatt; 
    private int mConnectionState = STATE_DISCONNECTED;
    private static final int STATE_DISCONNECTED = 0; //设备无法连接
    private static final int STATE_CONNECTING = 1;  //设备正在连接状态
    private static final int STATE_CONNECTED = 2;   //设备连接完毕
    public final static String ACTION_GATT_CONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED =
            "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE =
            "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA =
            "com.example.bluetooth.le.EXTRA_DATA";
    public final static UUID UUID_HEART_RATE_MEASUREMENT =
            UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);
    //通过BLE API的不同类型的回调方法
    private final BluetoothGattCallback mGattCallback =
            new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {//当连接状态发生改变
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {//当蓝牙设备已经连接
                intentAction = ACTION_GATT_CONNECTED;
                mConnectionState = STATE_CONNECTED;
                broadcastUpdate(intentAction);
                Log.i(TAG, "Connected to GATT server.");
                Log.i(TAG, "Attempting to start service discovery:" +
                        mBluetoothGatt.discoverServices());
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {//当设备无法连接
                intentAction = ACTION_GATT_DISCONNECTED;
                mConnectionState = STATE_DISCONNECTED;
                Log.i(TAG, "Disconnected from GATT server.");
                broadcastUpdate(intentAction);
            }
        }
        @Override
        // 发现新服务端
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }
        @Override
        // 读写特性
        public void onCharacteristicRead(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic,
                int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
        }
     ...
    };
...
}

然后返回到DeviceControlActivity的BroadcastReceiver来处理回调:

// 通过服务控制不同的事件
// ACTION_GATT_CONNECTED: 连接到GATT服务端
// ACTION_GATT_DISCONNECTED: 未连接GATT服务端.
// ACTION_GATT_SERVICES_DISCOVERED: 未发现GATT服务.
// ACTION_DATA_AVAILABLE: 接受来自设备的数据,可以通过读或通知操作获得。
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
            mConnected = true;
            updateConnectionState(R.string.connected);
            invalidateOptionsMenu();
        } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
            mConnected = false;
            updateConnectionState(R.string.disconnected);
            invalidateOptionsMenu();
            clearUI();
        } else if (BluetoothLeService.
                ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
            // 在用户接口上展示所有的services and characteristics
            displayGattServices(mBluetoothLeService.getSupportedGattServices());
        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
        }
    }
};

5.读写BLE特征值

android app完成与GATT服务端连接和发现services后,就可以读写支持的属性。


public class DeviceControlActivity extends Activity {
    ...
    // 演示如何遍历支持GATT Services/Characteristics
    // 这个例子中,我们填充绑定到UI的ExpandableListView上的数据结构
    private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null) return;
        String uuid = null;
        String unknownServiceString = getResources().
                getString(R.string.unknown_service);
        String unknownCharaString = getResources().
                getString(R.string.unknown_characteristic);
        ArrayList<HashMap<String, String>> gattServiceData =
                new ArrayList<HashMap<String, String>>();
        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
                = new ArrayList<ArrayList<HashMap<String, String>>>();
        mGattCharacteristics =
                new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
        // 循环可用的GATT Services.
        for (BluetoothGattService gattService : gattServices) {
            HashMap<String, String> currentServiceData =
                    new HashMap<String, String>();
            uuid = gattService.getUuid().toString();
            currentServiceData.put(
                    LIST_NAME, SampleGattAttributes.
                            lookup(uuid, unknownServiceString));
            currentServiceData.put(LIST_UUID, uuid);
            gattServiceData.add(currentServiceData);
            ArrayList<HashMap<String, String>> gattCharacteristicGroupData =
                    new ArrayList<HashMap<String, String>>();
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();
            ArrayList<BluetoothGattCharacteristic> charas =
                    new ArrayList<BluetoothGattCharacteristic>();
           // 循环可用的Characteristics.
            for (BluetoothGattCharacteristic gattCharacteristic :
                    gattCharacteristics) {
                charas.add(gattCharacteristic);
                HashMap<String, String> currentCharaData =
                        new HashMap<String, String>();
                uuid = gattCharacteristic.getUuid().toString();
                currentCharaData.put(
                        LIST_NAME, SampleGattAttributes.lookup(uuid,
                                unknownCharaString));
                currentCharaData.put(LIST_UUID, uuid);
                gattCharacteristicGroupData.add(currentCharaData);
            }
            mGattCharacteristics.add(charas);
            gattCharacteristicData.add(gattCharacteristicGroupData);
         }
    ...
    }
...
}



6.设置BLE通知

除了直接读写特征值,从机还有一种数据是通知型数据,即从机Notify数据,主机需要打开通知获取数据。

可以使用setCharacteristicNotification( )给一个特性设置通知。


private BluetoothGatt mBluetoothGatt;
BluetoothGattCharacteristic characteristic;
boolean enabled;
...
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
...
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
        UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);

当特征值发生改变时会触发回调方法,官方demo在回调中调用了更新广播的方法:


// 广播更新
public void onCharacteristicChanged(BluetoothGatt gatt,
        BluetoothGattCharacteristic characteristic) {
    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}


7.断开BLE连接

当APP完成BLE的通信后,应关闭BLE功能,及时释放占用的资源。

public void close() {
    if (mBluetoothGatt == null) {
        return;
    }
    mBluetoothGatt.close();
    mBluetoothGatt = null;
}