0

I wanna run my service only when device is not locked.How exactly it has to work:

  1. User runs the application.

  2. Then service is run

  3. Stop working when device is locked.
  4. When user unlock device service runs again.

I'm in need of help with first 3 points. Because fourth point can be done with ACTION_USER_PRESENT. Help me please.

Amit Vaghela
  • 22,772
  • 22
  • 86
  • 142
S.Drumble3
  • 59
  • 10

1 Answers1

2

1) You can start a Service by calling startService(Intent) from onCreate() or onStart() of your first Activity (alternatively, from onCreate() of your Application class).

2) Your Service is already running

3) To do so, you will need to detect the device lock event. The only approach I can think of here is listening for the ACTION_SCREEN_OFF. You can find a detailed example in the accepted answer of this question.

After you have detected the screen off action, you can stop your Service by calling stopService(Intent)

Community
  • 1
  • 1
Droidman
  • 11,485
  • 17
  • 93
  • 141
  • Hey. I've tried it ,so when I lock screen ACTION_SCREEN_OFF begins to work but when I unlock it my service starts again. I assume this is happened because when I unlock device ACTION_SCREEN_ON begins to work. – S.Drumble3 Feb 27 '16 at 02:03
  • @S.Drumble3 `when I unlock it my service starts again` - isn't that exactly what you were looking for? Or do you mean the service somehow starts twice on device unlock? – Droidman Feb 27 '16 at 09:41