Search code examples
androidservicebackgroundbindforeground

Unbinding a service when Android goes to Lock mode


As @hackbod stated here, I used the onStart/onStop couple to bind/unbind to my service. I want my service to stop running when in lock mode (to save battery) and to resume when coming back. However, Lock mode works with the onResume/onPause couple. So how do I do that?

Thanks


Solution

  • You can listen for broadcast when the screen turns on/off.

    registerReceiver(new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        // bind to service
      }
    }, new IntentFilter(Intent.ACTION_SCREEN_ON));
    
    registerReceiver(new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        // unbind from service
      }
    }, new IntentFilter(Intent.ACTION_SCREEN_OFF));