How to determine if an Android Service is running in the foreground?

后端 未结 6 899
眼角桃花
眼角桃花 2020-11-29 04:31

I have a service which I believe to have running in the foreground, How do I check if my implementation is working?

6条回答
  •  有刺的猬
    2020-11-29 05:12

    As of API 26, getRunningService() is deprecated.

    One solution now is to bind your Activity to your Service. Then you can call a method of your Service from your Activity, to check if it is running.

    1 - In your Service, create a class that extends Binder and returns your Service

      public class LocalBinder extends Binder {
            MyService getService() {
                return MyService.this;
            }
        }
    

    2 - In your Service, declare the binder

    private final IBinder binder = new LocalBinder();
    

    3 - In your Service, implement onBind(), which will return the Binder

      @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return binder;
        }
    

    4 - In your Service, create a method that check if it is running (for example check if variables are initialized)

      public boolean isRunning() {
            // If running
                return true;
            // If not running
                return false;
            
        }
    

    5 - In your Activity, create a variable that holds your Service

    private MyService myService;
    

    6 - Now, in your Activity, you can bind to your Service

    private void checkIfEnabled() {
        ServiceConnection connection = new ServiceConnection() {
    
            @Override
            public void onServiceConnected(ComponentName className,
                                           IBinder service) {
                MyService.LocalBinder binder = (MyService.LocalBinder) service;
                myService = binder.getService();
                
                // Calling your service public method
                if(myService.isRunning()) {
                    // Your service is enabled
                } else {
                    // Your service is disabled
                }
            }
    
            @Override
            public void onServiceDisconnected(ComponentName arg0) {
    
            }
        };
    
        // Bind to MyService
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }
    

    For more info, check Bound services overview from official documentation.

提交回复
热议问题