开发者

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 application ie, all the activities in the application. But the service should not consume the resources after user pressed Home key or Back开发者_StackOverflow中文版 button. Is there any elegant way to do that other than stopping the service in onPause() method of all the activities?


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();


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜