Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service goes to standby when device sleeps - Android

Envrionment: Eclipse
Language: Java (Android)

I have a bit of a problem, which I didn't realise until I tested my application out on a device. I always thought that services would continuously be running in the background, even when the phone's sleeping. I found out that this is not the case, so, my question is that does the service start up again once you wake your device up? And if not, how would I cause the service to start-up again.

Would I be able to wake the phone every 5 minutes or so, just to run my service, which will last 30 seconds to 1 minute. And then make the phone sleep again?

Thanks in advance.

EDIT: I am very new to Android programming and would really appreciate if someone would tell me how to use WakefulIntentService. I have a service that is searching for the user's GPS Location every so often, and when the phone goes to sleep, I want my service to still look for their location. How would I go about using the WakefulIntentService for this? And would I be able to use it in this scenario.

Thanks.

like image 321
user959631 Avatar asked Feb 17 '23 12:02

user959631


2 Answers

You need to hold the processor lock to keep your service running

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TAG");
wl.acquire();
// When you are done
wl.release();

And if your service is using Wi-Fi, you need another lock as well

WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiLock= wm.createWifiLock(WifiManager.WIFI_MODE_FULL, "TAG");
wifiLock.acquire();

// When you are done
wifiLock.release();

Remember to add android.permission.WAKE_LOCK in your manifest

like image 118
iTech Avatar answered Feb 20 '23 01:02

iTech


I have a service that is searching for the user's GPS Location every so often, and when the phone goes to sleep, I want my service to still look for their location. How would I go about using the WakefulIntentService for this? And would I be able to use it in this scenario.

WakefulIntentService is inappropriate here, as it is designed only to keep the device awake for a short period of time to do some work. It is not designed to keep the device awake for an indeterminate time, such as the time it takes to get a GPS fix.

I have a LocationPoller project that handles your scenario a bit better.

I am very new to Android programming

What you are trying to do is not a suitable project for somebody with your Android experience level, IMHO.

like image 35
CommonsWare Avatar answered Feb 20 '23 01:02

CommonsWare