2

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.

S.Drumble3
  • 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 Answers2

0

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.

Steven Wexler
  • 16,589
  • 8
  • 53
  • 80
0

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.

ELITE
  • 5,815
  • 3
  • 19
  • 29