Android 需要我的应用程序连接到两个BLE设备

Android 需要我的应用程序连接到两个BLE设备,android,bluetooth,connection,bluetooth-lowenergy,Android,Bluetooth,Connection,Bluetooth Lowenergy,我知道之前在这里已经讨论过了,但我从来没有找到一个具体的例子来说明这是如何实现的。到目前为止,我能够连接到一台设备,这就是我目前所拥有的: private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newSta

我知道之前在这里已经讨论过了,但我从来没有找到一个具体的例子来说明这是如何实现的。到目前为止,我能够连接到一台设备,这就是我目前所拥有的:

  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.");
            // Attempts to discover services after successful connection.
            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) {
            List<BluetoothGattService> services = gatt.getServices();
            gatt.readCharacteristic(services.get(2).getCharacteristics().get
                    (0));
            broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
        } else {
            Log.w(TAG, "onServicesDiscovered received: " + status);
        }
    }

    @Override
    public void onCharacteristicRead(final BluetoothGatt gatt,final
                                     BluetoothGattCharacteristic characteristic,
                                     int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
                    gatt.readCharacteristic(characteristic);
                }
            }).start();

        }
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic) {
        broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
    }
};
没有布局的主活动

public class MainActivity extends AppCompatActivity {
private Handler mHandler;
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private static final int REQUEST_ENABLE_BT = 1;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mHandler = new Handler();

    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();

    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice("E8:FF:34:49:A9:5B");
    final Intent intent = new Intent(this, DeviceControlActivity.class);
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
    startActivity(intent);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // User chose not to enable Bluetooth.
    if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
        finish();
        return;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

@Override
protected void onResume() {
    super.onResume();

    // Ensures Bluetooth is enabled on the device.  If Bluetooth is not currently enabled,
    // fire an intent to display a dialog asking the user to grant permission to enable it.
    if (!mBluetoothAdapter.isEnabled()) {
        if (!mBluetoothAdapter.isEnabled()) {
            Toast.makeText(getApplicationContext(), "Enable Bluetooth in phone settings.",
                    Toast.LENGTH_LONG).show();
        }
    }
}
}

使用代码管理服务生命周期的DeviceControlActivity

private final ServiceConnection mServiceConnection = new           ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder service) {
        mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();

        if (!mBluetoothLeService.initialize()) {
            Log.e(TAG, "Unable to initialize Bluetooth");
            finish();
        }
        // Automatically connects to the device upon successful start-up initialization.
        mBluetoothLeService.connect(mDeviceAddress);
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        mBluetoothLeService = null;
    }
};
在onCreate中建立连接

Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
    bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
接收方处理服务触发的各种事件

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);
            mConnectionState.setTextColor(Color.parseColor("#FF17AA00"));
            invalidateOptionsMenu();
        } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
            mConnected = false;
            updateConnectionState(R.string.disconnected);
            mConnectionState.setTextColor(Color.parseColor("#ff0000"));
            invalidateOptionsMenu();
            //clearUI();
        } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
            // Show all the supported services and characteristics on the user interface.
            //displayGattServices(mBluetoothLeService.getSupportedGattServices());
            List<BluetoothGattService> servs = mBluetoothLeService.getSupportedGattServices();
            for (int i = 0; servs.size() > i; i++) {

                List<BluetoothGattCharacteristic> charac = servs.get(i).getCharacteristics();
                for (int j = 0; charac.size() > i; i++) {
                     BluetoothGattCharacteristic ch = charac.get(i);
                    if (ch.getUuid() == chara) {
                        mBluetoothLeService.readCharacteristic(ch);
                        mBluetoothLeService.setCharacteristicNotification(ch, true);


                    }
                }
            }

        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
        }
    }
};
private final BroadcastReceiver mGattUpdateReceiver=new BroadcastReceiver(){
@凌驾
公共void onReceive(上下文、意图){
最后一个字符串action=intent.getAction();
if(蓝牙服务动作\关贸总协定\连接的相等动作){
mConnected=true;
updateConnectionState(R.string.connected);
mConnectionState.setTextColor(Color.parseColor(“#FF17AA00”);
无效操作菜单();
}else if(蓝牙服务操作\u GATT\u断开连接。等于(操作)){
mConnected=false;
updateConnectionState(R.string.disconnected);
mConnectionState.setTextColor(Color.parseColor(“#ff0000”);
无效操作菜单();
//clearUI();
}else if(BluetoothLeService.ACTION\u GATT\u SERVICES\u DISCOVERED.equals(ACTION)){
//在用户界面上显示所有支持的服务和特性。
//displayGattServices(mBluetoothLeService.getSupportedGattServices());
List servs=mBluetoothLeService.getSupportedGattServices();
对于(int i=0;servs.size()>i;i++){
List charac=servs.get(i).getCharacteristics();
对于(int j=0;charac.size()>i;i++){
BluetoothGattCharacteristic ch=charac.get(i);
if(ch.getUuid()==chara){
mBluetoothLeService.readCharacteristic(ch);
mBluetoothLeService.setCharacteristicNotification(ch,true);
}
}
}
}else if(BluetoothLeService.ACTION\u DATA\u AVAILABLE.equals(ACTION)){
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_数据));
}
}
};
经过一些研究,我的印象是我必须编辑BluetoothGattCallback才能管理2个连接。到目前为止,我所拥有的:

  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.");
            // Attempts to discover services after successful connection.
            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) {
            List<BluetoothGattService> services = gatt.getServices();
            gatt.readCharacteristic(services.get(2).getCharacteristics().get
                    (0));
            broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
        } else {
            Log.w(TAG, "onServicesDiscovered received: " + status);
        }
    }

    @Override
    public void onCharacteristicRead(final BluetoothGatt gatt,final
                                     BluetoothGattCharacteristic characteristic,
                                     int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
                    gatt.readCharacteristic(characteristic);
                }
            }).start();

        }
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic) {
        broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
    }
};
private final BluetoothGattCallback mGattCallback=new BluetoothGattCallback(){
@凌驾
连接状态更改的公共无效(蓝牙gatt gatt、int状态、int新闻状态){
串接;
if(newState==BluetoothProfile.STATE\u CONNECTED){
意向=行动与关贸总协定连接;
mConnectionState=连接状态;
广播更新(意向);
Log.i(标记“连接到GATT服务器”);
//尝试在成功连接后发现服务。
Log.i(标记“正在尝试启动服务发现:”+
mBluetoothGatt.discoverServices());
}else if(newState==BluetoothProfile.STATE\u已断开连接){
intentAction=动作与关贸总协定断开;
mConnectionState=状态\断开连接;
Log.i(标签,“与GATT服务器断开连接”);
广播更新(意向);
}
}
@凌驾
发现服务上的公共无效(Bluetooth gatt,int状态){
如果(状态==蓝牙GATT.GATT\U成功){
List services=gatt.getServices();
gatt.readCharacteristic(services.get(2).getCharacteristics().get
(0));
广播更新(发现行动、关税及贸易总协定服务);
}否则{
Log.w(标记“OnServicesDiscovery已接收:+状态);
}
}
@凌驾
特征上的公共无效阅读(最终蓝牙gatt,最终
蓝牙特征,
int状态){
如果(状态==蓝牙GATT.GATT\U成功){
新线程(newrunnable()){
@凌驾
公开募捐{
广播更新(动作数据可用,特征);
关贸总协定.特点(特点);
}
}).start();
}
}
@凌驾
特征变更后的公共无效(蓝牙gatt,
蓝牙(特征){
广播更新(动作数据可用,特征);
}
};

你看到这篇文章了吗?谢谢你的回复,是的,我回复了。但最详细的解决方案是使用队列,我希望避免这种情况。据我所知,问题是,在不创建队列的情况下,您无法确定设备不会相互覆盖。队列将在何处实现?看起来我必须重写服务