gpt4 book ai didi

android - bindservice 中的 onServiceConnected 只被调用一次

转载 作者:行者123 更新时间:2023-11-29 20:48:26 29 4
gpt4 key购买 nike

我正在尝试开发一个连接 android 和 RedBear BLE shield 的应用程序。

第一次一切正常。但是当我第二次尝试连接到设备时,它不起作用。 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;
}
};

最佳答案

这成功了。

@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);

}

关于android - bindservice 中的 onServiceConnected 只被调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29800835/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com