I'm a new one in android development.I wanna know how can start service if device is unlocked and stop it when it's not. I've found information about using ACTION_USER_PRESENT
it works fine but it needs that device was locked and then unlocked before my service could be started.

- 59
- 10
-
you can do it on screen on and off..for that use broadcast receiver of type `USER_PRESENT` – ELITE Feb 26 '16 at 01:43
-
Maybe you will find something useful in this [post](http://stackoverflow.com/questions/4522905/how-to-stop-service-when-action-screen-off) – Bui Quang Huy Feb 26 '16 at 01:46
2 Answers
You can listen for ACTION_SCREEN_ON and ACTION_SCREEN_OFF.
Notice you'll have to call registerReceiver to listen for these intents. Just registering them in AndroidManifest.xml will not work.

- 16,589
- 8
- 53
- 80
If you declare actions in Manifest
file for BroadcastReceiver
, then it'll work only when you register broadcast receiver. And when your application is closed, it'll not work. So register receiver in service.
For that create a service to register a receiver
public class UnlockService extends Service {
and register SCREEN_ON
AND SCREEN_OFF
BroadcastReceiver
onCreate
of that service
@Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenUnlockReceiver();
registerReceiver(mReceiver, filter);
}
and register the service in any activity from which you have to start detecting events.
Intent service = new Intent(CurrentActivity.this, UnlockService.class);
startService(service);
It'll register BroadcastReceiver
for checking SCREEN_ON
and SCREEN_OFF
events.
Then declare ScreenUnlockReceiver
public class ScreenUnlockReceiver extends BroadcastReceiver {
and write in onReceive
method
@Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
if(Intent.ACTION_SCREEN_ON.equals(action)) {
// start the service
} else if(Intent.ACTION_SCREEN_OFF.equals(action)) {
// stop the service
}
}
and done.

- 5,815
- 3
- 19
- 29
-
But when user unlocks device(press power button) he sees lock screen. (Here will work action_screen_on) So, in the end we got working service and locked phone. – S.Drumble3 Feb 26 '16 at 10:13
-
-
These receivers will be unregistered by the system after some time if registered this way. – John Sardinha Oct 20 '19 at 12:15