Skip to content Skip to sidebar Skip to footer

Android Service Running After Pressing Home Key

I have an Android service, created in OnCreate of first Activity of the application using StartService(). I need this service to be running throughout the life span of the applica

Solution 1:

Instead of using StartService, you can call bindService in onResume and unbindService in onPause. Your service will stop when there are no open bindings.

You'll need to create a ServiceConnection to get access to the service. For instance, here's a class nested inside MyService:

class MyService {
    public static class MyServiceConnection implements ServiceConnection {
        private MyService mMyService = null;

        public MyService getMyService() {
            return mMyService;
        }
        public void onServiceConnected(ComponentName className, IBinder binder) {
            mMyService = ((MyServiceBinder)binder).getMyService();
        }
        public void onServiceDisconnected(ComponentName className) {
            mMyService = null;
        }
    }

    // Helper class to bridge the Service and the ServiceConnection.
    private class MyServiceBinder extends Binder {
        MyService getMyService() {
            return MyService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyServiceBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return false;  // do full binding to reconnect, not Rebind
    }

    // Normal MyService code goes here.
}

One can use this helper class to get access to the service via:

MyServiceConnection mMSC = new MyService.MyServiceConnection();

// Inside onResume:
bindService(new Intent(this, MyService.class), mMSC, Context.BIND_AUTO_CREATE);

// Inside onPause:
unbindService(mMSC);

// To get access to the service:
MyService myService = mMSC.getMyService();

Solution 2:

You could do what Darrell suggests but put that code in a new class that extends Activity and then extend that on all your normal Activities.

I don't know any other more elegant way of achieving your goals.


Post a Comment for "Android Service Running After Pressing Home Key"