android连接多个设备,android - Android BLE-一次连接到多个设备 - SO中文参考 - www.soinside.com...

这里要求提供相关代码:(这里ArrayList包含已建立的外围设备)for(int i=0;i< Utility.selectedDeviceList.size();i++) {

Log.d(Utility.TAG,"state"+ Utility.selectedDeviceList.get(i).getmConnectionState());

if (Utility.selectedDeviceList.get(i).getmConnectionState() != Utility.CONNECTED) {

Log.d(Utility.TAG,"Connecting LeSerive::" + Utility.selectedDeviceList.get(i).getAddress());

Utility.mBluetoothLeService.connect(i, Utility.selectedDeviceList.get(i).getAddress());

}

}

此for循环是可运行接口的一部分,该接口在具有循环程序的处理程序内部被调用。public void run() {

Looper.prepare();

Looper mLooper = Looper.myLooper();

Log.d(Utility.TAG,"BLE Thread Started::");

mHandler = new Handler(mLooper) {

@Override

public void handleMessage(Message msg) {

switch (msg.what) {

case Utility.BLE_SYNC:

Log.d(Utility.TAG,"BLE Sync Connecting::");

mHandler.post(SynState);

break;

}

};

Looper.loop();

}

我之所以使用这种方法,是因为外围设备之间需要大量的通信来发送和接收来自它们的数据。

这是服务内部的连接方法:public boolean connect(int tag,final String address) {

if (mBluetoothAdapter == null || address == null) {

Log.w(Utility.TAG, "BluetoothAdapter not initialized or unspecified address.");

return false;

}

Utility.selectedDeviceList.get(tag).setmConnectionState(Utility.CONNECTING);

if( Utility.selectedDeviceList.get(tag).getmBluetoothGatt()==null){

Log.w(Utility.TAG, "new connect :: "+ Utility.selectedDeviceList.get(tag).getAddress());

BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

if (device == null) {

Log.w(Utility.TAG, "Device not found. Unable to connect.");

return false;

}

try {

Utility.selectedDeviceList.get(tag).setmBluetoothGatt(device.connectGatt(this, false, mGattCallback));

}

catch (Exception e)

{

e.printStackTrace();

Log.d(Utility.TAG,"ConnectGatt exception caught");

}

}

return true;

}

这是mGattCallBack:private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

@Override

public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

}

@Override

public void onServicesDiscovered(BluetoothGatt gatt, int status) {

Log.d(Utility.TAG, "onServicesDiscovered");

}

@Override

public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic,int status) {

}

@Override

public void onCharacteristicWrite(BluetoothGatt gatt,

BluetoothGattCharacteristic characteristic, int status) {

super.onCharacteristicWrite(gatt, characteristic, status);

Log.d(Utility.TAG,">>onCharacteristicWrite");

}

@Override

public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {

}

};

希望它为您清除了几件事

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值