ฉันมี 3 องค์ประกอบ
กิจกรรม1 มีปุ่มสำหรับเชื่อมต่อและยกเลิกการเชื่อมต่อ BLE
Activity2 จำเป็นต้องรับข้อมูลจากอุปกรณ์ BLE
บริการ ตรรกะการเชื่อมต่อทั้งหมด (เช่น getRemoteDevice(),connectGatt ฯลฯ) เป็นของบริการ
กิจกรรม1 กำลังเชื่อมต่อกับอุปกรณ์ BLE โดยผูกบริการ
Intent gattServiceIntent = new Intent(mContext,BleService.class);//In Activity1 context
bindService(gattServiceIntent, mServiceConnection,BIND_AUTO_CREATE);
และทำการเชื่อมต่อกับอุปกรณ์ ble ทันทีที่กดปุ่ม
ตอนนี้เมื่อฉันย้ายจาก Activity1 เป็น Activity2 ฉันกำลังยกเลิกการเชื่อมโยงบริการใน Activity1
mContext.unbindService(mServiceConnection);//In Activity1 context
ตอนนี้ฉันจะใช้การเชื่อมต่ออุปกรณ์ BLE ที่มีอยู่ใน Activity2 ได้อย่างไร
วิธีแก้ปัญหาชั่วคราวของฉัน:
ฉันกำลัง กำลังเชื่อมต่อ อุปกรณ์ BLE อีกครั้งเมื่อย้ายไปยัง Activity2 โดยอินสแตนซ์บริการใหม่ที่เชื่อมโยงกับมันจากบริบท Activity2 . (ซึ่งฉันไม่ต้องการ)
ใน Activity2 ฉันกำลังตรวจสอบว่าบริการของฉันทำงานอยู่แล้วหรือไม่ หากไม่ได้ทำงานอยู่ ฉันจะเชื่อมโยงบริการอีกครั้งจากบริบท Activity2
if(!isMyServiceRunning(BleWrapper.class)){
Intent wrapperServiceIntent = new Intent(mContext,BleWrapper.class);
bindService(wrapperServiceIntent,mBLEWrapperServiceConnection,BIND_AUTO_CREATE);
}else{
Log.w(LOGTAG, "Service already connected. In onCreate");
}
ทริกเกอร์การเชื่อมต่อใน onServiceConnected() ภายใต้การโทรกลับ ServiceConnection
@Override
public void onServiceConnected(ComponentName componentName,IBinder service) {
mBluetoothLeService = ((BleWrapper.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
showAlertDialog(getString(R.string.ble_not_supported_on_this_device));
}else {
mBluetoothLeService = BleWrapper.getInstance();
}
mBluetoothLeService.connect(/*address from shared preference*/); //Reconnecting to the same device using address stored in Shared pref
}
สำหรับการตรวจสอบว่าบริการของฉันทำงานอยู่หรือไม่
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
แต่ฟังก์ชัน isMyServiceRunning() จะคืนค่าเท็จเสมอ หมายความว่าบริการถูกตัดการเชื่อมต่อเมื่อย้ายจาก กิจกรรม 1 เป็น กิจกรรม 2
วิธีแก้ปัญหาใด ๆ สำหรับการรักษาการเชื่อมต่ออุปกรณ์ ble ข้ามกิจกรรมต่างๆ?