|
请看源码如下:
public void connect(UZModuleContext moduleContext, String address) {
/*if ((address == null) || (address.length() == 0)) {
connectCallBack(moduleContext, false, 1, "null address");
return;
}
try {
if (this.bluetoothGatt != null) {
this.bluetoothGatt.disconnect();
this.bluetoothGatt.close();
}
final BluetoothDevice device = this.mBluetoothAdapter.getRemoteDevice(address);
((Activity) this.mContext).runOnUiThread(new Runnable() {
public void run() {
AndroidBle.this.bluetoothGatt = device.connectGatt(AndroidBle.this.mContext, false, AndroidBle.this.mBluetoothGattCallback);
AndroidBle.this.bluetoothGatt.requestMtu(512);
}
});
} catch (Exception e) {
connectCallBack(moduleContext, false, 2, "Exception");
}*/
//存储连接接口的 moduleContext
mConnectCallBackMap.put(address, moduleContext);
if (mBluetoothAdapter == null || address == null) {
Log.i(TAG, "BluetoothAdapter not initialized or unspecified address.");
connectCallBack(moduleContext, false, 1, "null address",null);
return;
}
//获得给定的蓝牙硬件地址的蓝牙设备对象 ,也就是我们要连接的那个设备的device;
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.i(TAG, "Device not found. Unable to connect.");
connectCallBack(moduleContext, false, 2, "device is null object",null);
return;
}
/***
* 下方代码是为了防止手机最多能连接五次到六次的上限,所以进入时先判断,连接过没有
* 有的话先关闭掉,重新创建一个新的连接;
*/
try {
if (mBluetoothGatt != null) {
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
}
//此代码连接操作
if (Build.VERSION.SDK_INT >= 23) {
mBluetoothGatt = device.connectGatt(mContext, false, mBluetoothGattCallback);
AndroidBle.this.mBluetoothGatt.requestMtu(512);
} else {
mBluetoothGatt = device.connectGatt(mContext, false, mBluetoothGattCallback);
mBluetoothGatt.requestMtu(512);
}
Log.i(TAG, "Trying to create a new connection.");
} catch (Exception e) {
connectCallBack(moduleContext, false, 2, "Exception",null);
}
}
|
|