vendredi 1 juin 2018

starting and binding a service in singleton Application class

I have a singleton Application class, which starts and binds to this bluetoothService class. Whenever I need to use the service from any activity I am passing the applicationContext() to start this service. Wondering if I am doing anything wrong by doing so ? One problem I noticed is if I make the serviceclass instance in the Application to null after disconnect() and close(), the following code fails to bind to the service when called from any activity i.e mServiceConnection methods are not called:

/* start bluetooth service */
    public void startService(Context context){
        this.context = context;

        if (mBluetoothLeService == null){
            Intent gattServiceIntent = new Intent(context, BluetoothLeService.class);
            context.bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        }

    }



/* Code to manage Service lifecycle. */
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

Aucun commentaire:

Enregistrer un commentaire