Android service stops working when phone is locked

I have an application that starts a service. The service has a timer and a notification appears every 30 seconds. I notice the following behavior:

  • if the screen displays notifications in order (even if the application is in the background)
  • If the screen is turned off (by the power button or by itself), notifications will not be displayed
  • if the screen is off, but I have a debug that displays notifications.

How can I make the service work with the screen off.

(The actual application only checks whether the notification should be checked every 30 seconds, but for testing purposes, the above scenario is fine)

Thanks!

+7
android
source share
3 answers

I had some kind of problem.

You can use WakeLock to get the job done! Something like that:

PowerManager pm = (PowerManager)getApplicationContext().getSystemService( getApplicationContext().POWER_SERVICE); WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); wl.acquire(); 

Then use this:

 wl.release(); 

to free wakelock.

Do not fake:

<uses-permission android:name="android.permission.WAKE_LOCK" />

manifesto!

+4
source share

Not. This would be the perfect way to quickly drain your phone’s battery. If the phone is asleep, let it sleep if you do not have a GOOD reason (in this case you will use the AlarmManager for a one-time wake-up in the future).

I don’t know what you are trying to achieve, but you need to use a completely different approach. Tickling the net would be a good idea, for example, assuming that you can only live with your app with 2.2+.

+2
source share

If you really want your service to start every 30 seconds when the device is locked, you should schedule your alarm with type ELAPSED_REALTIME_WAKEUP . But be careful, this will certainly drain the batteries quickly!

+1
source share

All Articles