Android service running after pressing Home key

前端 未结 2 1764
鱼传尺愫
鱼传尺愫 2021-01-07 07:04

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

相关标签:
2条回答
  • 2021-01-07 07:27

    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 讨论(0)
  • 2021-01-07 07:31

    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();
    
    0 讨论(0)
提交回复
热议问题