title: Starting a service when the device's screen is unlocked in Android
body: <p>I would like to run my service when the screen is unlocked and stop it when the screen is locked. I looked into <a href="https://stackoverflow.com/questions/4522905/how-to-stop-service-when-action-screen-off">these answers</a> and implemented them. <strong>However, when I lock my screen the service stops as required, but when I unlock the screen it doesn't starts again.</strong></p>
  
  <p>The code for to run this service is as follows:</p>
  
  <pre><code>public class PhonePositionService extends Service {
  @Override
      public void onCreate() {
      //ADDED CODE
      IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
      filter.addAction(Intent.ACTION_SCREEN_OFF);
      BroadcastReceiver mReceiver = new BootCompletedIntentReceiver();
      registerReceiver(mReceiver, filter);
      {...}
      }
  @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
      int icon = R.drawable.ic_stat_bright;
      startForeground(NOTIFICATION_ID, getCompatNotification(icon));
      if (backgroundThread != null) {
        backgroundThread.start();
      }
      return START_STICKY;
    }
  }
  </code></pre>
  
  <p>In some other file, my broadcast receiver code is as follows:</p>
  
  <pre><code>public class BootCompletedIntentReceiver extends BroadcastReceiver {
   @Override
   public void onReceive(Context context, Intent intent) {
     String action = intent.getAction();
     if(Intent.ACTION_SCREEN_ON.equals(action)) {
       // start the service
       Intent pushIntent = new Intent(context, PhonePositionService.class);
       context.startService(pushIntent);
     } else if(Intent.ACTION_SCREEN_OFF.equals(action)) {
       // stop the service
       Intent pushIntent = new Intent(context, PhonePositionService.class);
       context.stopService(pushIntent);
     }
    if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
      Intent pushIntent = new Intent(context, PhonePositionService.class);
      context.startService(pushIntent);
    }
   }
  }
  </code></pre>
  
  <p>Then why is it so that when I unlock my phone the service does not start again?</p>