【Android开发】BLE开发流程

  • Post author:
  • Post category:其他




常见API调用

Android 平台提供了支持低功耗蓝牙作为主机、从机的API,开发的APP可以发现设备、查询服务和传输信息。



扫描发现BLE设备

我们通常使用startScan()的方法扫描BLE设备,所扫描的结果是在ScanCallbak的回调函数返回出来的。作为BLE APP是会提供一个activity用于显示一个扫描设备的列表给用户。如下示例,如何开启扫描和停止扫描的。

private BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
private boolean scanning;
private Handler handler = new Handler();
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
private void scanLeDevice() {
  if (!scanning) {// Stops scanning after a predefined scan period.
     handler.postDelayed(new Runnable() {   @Override
       public void run() {
                scanning = false;
                bluetoothLeScanner.stopScan(leScanCallback);
            }
        }, SCAN_PERIOD);
        scanning = true;
        bluetoothLeScanner.startScan(leScanCallback);
    } else {
        scanning = false;
        bluetoothLeScanner.stopScan(leScanCallback);
    }
}

我们将扫描的结果,添加到适配器列表里:

private LeDeviceListAdapter leDeviceListAdapter = new LeDeviceListAdapter();// Device scan callback.
private ScanCallback leScanCallback =
        new ScanCallback() {  @Override
            public void onScanResult(int callbackType, ScanResult result) 
            {
           super.onScanResult(callbackType, result);                   leDeviceListAdapter.addDevice(result.getDevice());          leDeviceListAdapter.notifyDataSetChanged();
            }
        };



连接GATT服务

我们通常使用

bluetoothGatt = device.connectGatt(this, false, gattCallback);

API通过BLE设备去连接主机的GATT服务

一、设置绑定服务

二、设置蓝牙适配器

三、连接一个设备

四、声明GATT回调

五、连接GATT服务

六、广播更新

private void broadcastUpdate(final String action) {
    final Intent intent = new Intent(action);
    sendBroadcast(intent);
}
class BluetoothService extends Service {
    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";
    private static final int STATE_DISCONNECTED = 0;p
    private static final int STATE_CONNECTED = 2;
    private int connectionState;
    ...
    private final BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // successfully connected to the GATT Server
             connectionState = STATE_CONNECTED;
             broadcastUpdate(ACTION_GATT_CONNECTED);
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // disconnected from the GATT Server
             connectionState = STATE_DISCONNECTED;
             broadcastUpdate(ACTION_GATT_DISCONNECTED);
            }
        }
    };}

七、侦听活动中的更新

class DeviceControlsActivity extends AppCompatActivity {
...
    private final BroadcastReceiver gattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
             connected = true;
             updateConnectionState(R.string.connected);
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                connected = false;
           updateConnectionState(R.string.disconnected);
            }
        }
    };
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(gattUpdateReceiver, makeGattUpdateIntentFilter());
        if (bluetoothService != null) {
            final boolean result = bluetoothService.connect(deviceAddress);
            Log.d(TAG, "Connect request result=" + result);
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(gattUpdateReceiver);
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();     intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);      intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        return intentFilter;
    }
}

八、关闭GATT连接

class BluetoothService extends Service {
...
      @Override
      public boolean onUnbind(Intent intent) {
          close();
          return super.onUnbind(intent);
      }
      private void close() {
          if (bluetoothGatt == null) {
              Return;
          }
          bluetoothGatt.close();
          bluetoothGatt = null;
      }
}



BLE数据传输

在已经连接BLE GATT服务的情况下,我们可以发现设备上的服务,从设备上获取数据和在GATT特征发生改变时请求通知。

一、发现服务

class BluetoothService extends Service {
    public final static String ACTION_GATT_SERVICES_DISCOVERED =
            "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";

    ...
    private final BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // successfully connected to the GATT Server
                connectionState = STATE_CONNECTED;
                broadcastUpdate(ACTION_GATT_CONNECTED);
                // Attempts to discover services after successful connection.
                bluetoothGatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // disconnected from the GATT Server
                connectionState = STATE_DISCONNECTED;
                broadcastUpdate(ACTION_GATT_DISCONNECTED);
            }
        }

        @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);
            }
        }
    };
}

二、读BLE特性

三、接收GATT通知



版权声明:本文为weixin_43060137原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。