Andorid BLE的连接多个设备的实现

最近回头一看,还有很多公司是在做智能家居的项目,当然 , 这必修回使用到BLE的通讯协议。目前关于BLE的帖子的千千万万,但是多连接的却是很少的,所以,这篇就来分析下BLE的多连接

1,BLE设备得我扫描。这个直接调用btAdapter的startLeScan即可。

相对应得,停止扫描调用stopLeScan().

// 开始扫描	
public void startLeScan() {
    if (mBluetoothAdapter != null) {
	mBluetoothAdapter.startLeScan(mLeScanCallback);
   }
}

//停止扫描
public void stopLeScan() {
	if (mBluetoothAdapter != null) {
		mBluetoothAdapter.stopLeScan(mLeScanCallback);
	}
}

2, 调用开始和停止后, 都要实现mLeScanCallback,

	//扫描回调
	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
		@Override
		public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
			String str  = device.getAddress();
			String name = device.getName();
			Log.d(TAG, "--扫描-->"+name+"--"+str+"--count-->"+count+"--Address-->"+lastAddress+"--rssi--->"+rssi/**+"--uuid-->"+guuid_record(scanRecord)**/);
			
			if (count < 2) { // 如果连接上两个设备就不去连了
				if(name == null) return;
				if (guuid_record(scanRecord).equals(keyUUID) || guuid_record(scanRecord).equals(earUUID)) {   // 连接指定的uuid
					
					if (!str.equalsIgnoreCase(lastAddress)) {   // 连接上的同一地址不处理
						if (connect(device, guuid_record(scanRecord))) {
							Log.i(TAG, "---连接上的--->");
						}
					}else{
						Log.i(TAG, "---地址相等---->");
					}
				}
			} else{
				Log.i(TAG, "---count >= 2---->");
			}
		}
	};
//扫描的回调中截取UUID
	private UUID guuid_record(byte[] scanRecord) {
		final int serviceOffset = 5;
		try {
			byte[] service = ArrayUtils.subarray(scanRecord, serviceOffset, serviceOffset + 16);
			ArrayUtils.reverse(service);
			String discoveredServiceID = bytesToHex(service);
			String realId = discoveredServiceID.substring(0, 8) + "-" + discoveredServiceID.substring(8, 12) + "-" + discoveredServiceID.substring(12, 16) + "-" + discoveredServiceID.substring(16, 20) + "-"+ discoveredServiceID.substring(20);
			return UUID.fromString(realId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

3,看看connect().

//连接
	public boolean connect(BluetoothDevice device, UUID uuid) {
		String connectAddress =  device.getAddress();
		// 这里弄的一个重连机制 没作用 ,这里注释为断开重连做个参考
		/*if (bGettHearset != null && uuid.toString().startsWith("要连接的设备UUID地址") && connectAddress.equals(lastAddress)) {
			lastAddress = connectAddress;
			
			return bGettHearset.connect();
		}
		
		
		if(bGettKeyboard != null && uuid.toString().startsWith("要连接的设备UUID地址") && connectAddress.equals(lastAddress)){
			lastAddress = connectAddress;
			
			return bGettKeyboard.connect();
		}*/
		
	   final BluetoothDevice deviceTemp = mBluetoothAdapter.getRemoteDevice(connectAddress);
	   
	    //遥控器建立GATT连接
	   if(bGettKeyboard == null && uuid.toString().startsWith("要连接的设备UUID地址")){
		   bGettKeyboard = deviceTemp.connectGatt(mContext, false, gattKeyboard); // 这里是个最关键的一个回调,连接成功后接收数据就是从这个回调
		   if(bGettKeyboard != null){
			   lastAddress = connectAddress;
			   count++;
			  
			   return true;
		   }  
	   }
	   
	   //耳机建立GATT连接
	   if(bGettHearset == null && uuid.toString().startsWith("要连接的设备UUID地址")){
		   bGettHearset = deviceTemp.connectGatt(mContext, false, gettHearset); // 这里是个最关键的一个回调,连接成功后接收数据就是从这个回调
		   if(bGettHearset != null) {
			   lastAddress = connectAddress;
			   count++;
			
			   return true;
		   } 
	   }else{
		   
	   }
		return false;
	}
	

4, Gatt回调

private BluetoothGattCallback gettHearset = new BluetoothGattCallback() {
		@Override
		public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
			if (newState == BluetoothProfile.STATE_CONNECTED) {
				bGettHearset.discoverServices();
				if(iStatus != null)   iStatus.statusInfo(newState, earUUID);
				if(mIntent != null)   mContext.startService(mIntent);
				
				
			} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
				lastAddress = "****";
				count--;
				bGettHearset.close();
				bGettHearset = null;
				
				if (iStatus != null) 	 iStatus.statusInfo(newState, earUUID);
				
				if (mIntent != null)     mContext.stopService(mIntent);
				
			}
		}

		@Override
		public void onServicesDiscovered(BluetoothGatt gatt, int status) {
			List<BluetoothGattService> earServiceList =  bGettHearset.getServices();
			
			 for (BluetoothGattService earGattService : earServiceList) {
				 if(earGattService.getUuid().equals(earUUID)){
					 List<BluetoothGattCharacteristic> earValueList = earGattService.getCharacteristics();
					 for (BluetoothGattCharacteristic earValue : earValueList) {
						 if(earValue.getUuid().equals(earWriteUUID)){
							 bGettHearset.setCharacteristicNotification(earValue, true); 
							 break; 
						 }
					 }
				 }
			 }
		}

@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
			byte[] new_data = characteristic.getValue();
			while (handle_buffer(OP_WRITE, new_data, new_data.length) != null) { // 获取数据
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
		}
	};

这个流程下来就是这些。如果需要了解BLE的理论,看看其他贴子。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值