android 低功耗藍牙BLE多連接,多設備通信

現在很多做藍牙APP的都需要同時連接多個設備,那該怎么才能同時管理多個設備呢?以下是本人的方法,主要是通過ArrayMap來管理不同設備的BluetoothGatt,然后使用各自的BluetoothGatt來和從機進行數據交互,我們可以綁定該service進行方法的調用。

public class BluetoothLeService2 extends Service {

private ArrayMap<String, BluetoothGatt> gattArrayMap = new ArrayMap<>();
private BluetoothAdapter mBluetoothAdapter;

@Override
public void onCreate() {
    super.onCreate();
    initBluetooth();
}

/**
 * 藍牙是否開啟
 */
public boolean isBluetoothEnabled() {
    return mBluetoothAdapter.isEnabled();
}


private void initBluetooth() {
    BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, Service.START_FLAG_RETRY, startId);
}


@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}


public class LocalBinder extends Binder {
    public BluetoothLeService2 getService() {
        return BluetoothLeService2.this;
    }
}

private final IBinder mBinder = new LocalBinder();

@Override
public boolean onUnbind(Intent intent) {
    return super.onUnbind(intent);
}


/**
 * 連接設備
 *
 * @param address 設備地址
 */
public synchronized void connect(final String address) {
    BluetoothGatt gatt = gattArrayMap.get(address);
    if (gatt != null) {
        gatt.disconnect();
        gatt.close();
        gattArrayMap.remove(address);
    }
    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    if (device == null) return;
    device.connectGatt(this, false, mGattCallback);
}

//藍牙連接,數據通信的回掉
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(final BluetoothGatt gatt, int status, int newState) {
        String address = gatt.getDevice().getAddress();
        if (status == BluetoothGatt.GATT_SUCCESS) {
            if (newState == BluetoothGatt.STATE_CONNECTED) {// 連接成功
                gatt.discoverServices();// 尋找服務
                gattArrayMap.put(address, gatt);
                Log.i("yushu", "connect succeed: ");
            } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {// 斷開連接
                onDisConnected(gatt, address);
                Log.i("yushu", "connect fail ");
            }
        } else {
            onDisConnected(gatt, address);
            Log.i("yushu", "connect fail ");
        }
    }


    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            enableNotification(gatt);//notification
        }
    }


    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        byte[] value = characteristic.getValue();
/**
 * 這里可以拿到設備notification回來的數據
*/

    }


    @Override
    public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
        super.onReadRemoteRssi(gatt, rssi, status);
        if (status == BluetoothGatt.GATT_SUCCESS) {

        }
    }
};


private void onDisConnected(BluetoothGatt gatt, String address) {
    gatt.disconnect();
    gatt.close();
}


/**
 * 使能通知
 */
private void enableNotification(BluetoothGatt mBluetoothGatt) {
    if (mBluetoothGatt == null) return;
    BluetoothGattService ableService = mBluetoothGatt.getService(UUIDUtils.UUID_LOST_SERVICE);
    if (ableService == null) return;
    BluetoothGattCharacteristic TxPowerLevel = ableService.getCharacteristic(UUIDUtils.UUID_LOST_ENABLE);
    if (TxPowerLevel == null) return;
    setCharacteristicNotification(mBluetoothGatt, TxPowerLevel, true);
}

/**
 * 使能通知
 */
private void setCharacteristicNotification(BluetoothGatt mBluetoothGatt, BluetoothGattCharacteristic characteristic, boolean enabled) {
    if (mBluetoothGatt == null) return;
    mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
    if (UUIDUtils.UUID_LOST_ENABLE.equals(characteristic.getUuid())) {
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUIDUtils.CLIENT_CHARACTERISTIC_CONFIG);
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
    }
}


/**
 * 寫數據到硬件,這里的服務UUID和特這的UUID參考硬件那邊,兩邊要對應
 */
public synchronized void writeDataToDevice(byte[] bs, String address) {
    BluetoothGatt mBluetoothGatt = gattArrayMap.get(address);
    if (mBluetoothGatt == null) return;
    BluetoothGattService alertService = mBluetoothGatt.getService(UUIDUtils.UUID_LOST_SERVICE);
    if (alertService == null) return;
    BluetoothGattCharacteristic alertLevel = alertService.getCharacteristic(UUIDUtils.UUID_LOST_WRITE);
    if (alertLevel == null) return;
    alertLevel.setValue(bs);
    alertLevel.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
    mBluetoothGatt.writeCharacteristic(alertLevel);
}


public boolean readRssi(String address) {
    BluetoothGatt bluetoothGatt = gattArrayMap.get(address);
    return bluetoothGatt != null && bluetoothGatt.readRemoteRssi();
}


public void remove(String address) {
    BluetoothGatt bluetoothGatt = gattArrayMap.get(address);
    if (bluetoothGatt != null) {
        bluetoothGatt.disconnect();
        bluetoothGatt.close();
        gattArrayMap.remove(address);
    }
}

public void disConnect(String address) {
    BluetoothGatt bluetoothGatt = gattArrayMap.get(address);
    if (bluetoothGatt != null) {
        bluetoothGatt.disconnect();
        gattArrayMap.remove(address);
    }
}


@Override
public void onDestroy() {
    gattArrayMap.clear();
    super.onDestroy();
}
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容