I have 3 components.
Activity1 has a button to connect and disconnect a BLE connection
Activity2 Required to receive data from a BLE device.
Service . All connection logic (e.g. getRemoteDevice (), connectGatt, etc.) belongs to the service.
Activity1 connects to the BLE device, linking the service.
Intent gattServiceIntent = new Intent(mContext,BleService.class);
bindService(gattServiceIntent, mServiceConnection,BIND_AUTO_CREATE);
and connects to the device as soon as the button is pressed.
Now, when I switch from Activity1 to Activity2 , I turn off the service in Activity1 .
mContext.unbindService(mServiceConnection);
BLE Device 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();
}
,
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() false. , Activity1 Activity2
?