我正在尝试开发一个连接android和RedBear BLE盾的应用程序。
第一次一切正常。但是,当我第二次尝试连接到设备时,它没有工作。 OnServiceConnected()第一次调用,但第二次调用它。
如果我杀了应用程序并再次启动它,第一次一切正常,但连接第二次失败。
public TransreceiverInterface registerIntent(Intent intent) {
Log.d(TAG, "[registerIntent] Trying BluetoothTransreceiver");
String action = intent.getAction();
if ("BLUETOOTHLE".equals(action)) {
Log.d(TAG,
"[registerIntent] Discovered BLUETOOTHLE ... registering intent");
device = intent.getParcelableExtra("EXTRAS_DEVICE");
Log.d(TAG,
"[registerIntent] Register intent fordevice ["
+ device.getName() + "] [" + device.getAddress()
+ "]");
Log.d(TAG, "[registerIntent] Creating GATT service intent");
Intent gattServiceIntent = new Intent(context, RBLService.class);
Log.d(TAG, "[registerIntent] Binding service");
boolean status = context.getApplicationContext().bindService(
gattServiceIntent, mServiceConnection,
Context.BIND_AUTO_CREATE);
if (status) {
Log.i(TAG, "Starting Service (just in case)");
context.startService(gattServiceIntent);
Log.d(TAG, "[registerIntent] Registering receiver");
context.registerReceiver(mGattUpdateReceiver,
makeGattUpdateIntentFilter());
Log.d(TAG, "[registerIntent] Registering receiver done");
} else {
Log.d(TAG, "[registerIntent] Could not bind service");
return null;
}
return this;
}
return null;
}
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName,
IBinder service) {
Log.d(TAG, "onServiceConnected");
mBluetoothLeService = ((RBLService.LocalBinder) service)
.getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
}
// Automatically connects to the device upon successful start-up
// initialization.
Log.d(TAG, "Connecting Service to device [" + device.getName()
+ "]");
mBluetoothLeService.connect(device.getAddress());
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.d(TAG, "onServiceDisconnect called");
mBluetoothLeService = null;
}
};
答案 0 :(得分:1)
这就是诀窍。
@Override
public void disconnect() {
serviceReady = false;
Log.d(TAG, "unregister gatt update receiver");
context.unregisterReceiver(mGattUpdateReceiver);
Log.d(TAG, "diconnect BT service");
mBluetoothLeService.disconnect();
Log.d(TAG, "closing service connection");
mBluetoothLeService.close();
Log.d(TAG, "closing service connection");
context.getApplicationContext().unbindService(mServiceConnection);
}