Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android service stops working when phone locked

Tags:

android

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

  • if the screen is on the notifications are shown ok (even if the app is in background)
  • if the screen is off (by power button or by itself) the notifications won't show
  • if the screen is off but I have the debugging running the notifications appear

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

(The actual app only checks if a notification should be checked every 30 seconds, but for testing purposes, the above scenario is ok)

Thanks!

like image 952
Cristian Avatar asked Nov 09 '10 22:11

Cristian


3 Answers

I had the some problem.

You may use the WakeLock to do the work! Something like this:

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 release the wakelock.

Don't forger to add:

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

to the manifest!

like image 141
aF. Avatar answered Nov 02 '22 22:11

aF.


You don't. That would be the perfect way to quickly drain the phone's battery. If the phone is sleeping, let it sleep, unless you have a GOOD reason not to (in which case you use the AlarmManager for a one-time wake-up call in the future).

I don't know what you're trying to achieve, but you need to use a completely different approach. A network tickle would be a good idea, for example, assuming you can live with your app being 2.2+ only.

like image 24
EboMike Avatar answered Nov 02 '22 21:11

EboMike


If you really want your service to run every 30s when the device is locked, you have to schedule your alarm with type ELAPSED_REALTIME_WAKEUP . But beware, this will certainly drain devices batteries to death rapidly!

like image 22
Kevin Gaudin Avatar answered Nov 02 '22 22:11

Kevin Gaudin