I would like to run my service when the screen is unlocked and stop it when the screen is locked. I looked into these answers and implemented them. However, when I lock my screen the service stops as required, but when I unlock the screen it doesn't starts again.
The code for to run this service is as follows:
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;
}
}
In some other file, my broadcast receiver code is as follows:
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);
}
}
}
Then why is it so that when I unlock my phone the service does not start again?