How to establish a BLE connection that is associated with using a service to use as part of an action without stopping service or shutting down?

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);//In Activity1 context
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);//In Activity1 context

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(/*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() false. , Activity1 Activity2

?

+4
1

LocalBinder ( ) . №1 , bindservice unbindservice . №2 bindservice , . bluetooth. . .

+3

Source: https://habr.com/ru/post/1614838/


All Articles