Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a service in the background forever..? Android

Tags:

android

I am doing a Battery Consuming research on the Android phone. I want to run a Battery Check every 10 min till the battery totally dies. I have been having problems to make it work.

At my first try, I use a timer in a service class, and schedule the battery check every 10 mins. But soon I found that the service got paused when the screen goes off.

Then I try to use AlarmService, I use a alarm call to wake my service every 10 mins and to check the battery level and save the data to a file on the sdcard. It works with the screen off. However, I only got data of 9 hours...it seems that the AlarmService stop at some point after several hours. I don't know why it is like this, has the system killed it for memory issues?

So my question is, has anyone written some service to run (like forever) in the background before? How do you do it and I'd appreciate very much for a sample code?

I am currently reading some posts saying that there's a partial wake lock I can use to keep the service alive.. is this the correct way to do it?

Thanks a lot and I hope I can get some useful answers here.

like image 781
sunocky Avatar asked Feb 04 '23 06:02

sunocky


2 Answers

At my first try, I use a timer in a service class, and schedule the battery check every 10 mins. But soon I found that the service got paused when the screen goes off.

You probably did not hold a WakeLock, so the device fell asleep.

it seems that the AlarmService stop at some point after several hours

I rather doubt it.

So my question is, has anyone written some service to run (like forever) in the background before?

It is not possible to create a service that will run forever. It should be possible to create a scheduled task via AlarmManager that will be invoked "forever".

I am currently reading some posts saying that there's a partial wake lock I can use to keep the service alive.. is this the correct way to do it?

I'm not sure what "it" is. But, if you want to keep the device awake -- whether for your first approach or just while you are doing work triggered by an AlarmManager -- you need to hold a WakeLock.

Here is a project that does almost exactly what you describe for the AlarmManager, minus checking the battery level, but using a WakefulIntentService to ensure the device stays awake. If you cannot get this code to run until the battery shuts down, join the cw-android Google Group and report your findings, and I'll take a look at it.

like image 174
CommonsWare Avatar answered Feb 06 '23 14:02

CommonsWare


http://github.com/commonsguy/cw-advandroid/tree/master/SystemServices/Alarm/

like image 39
Vishal Khakhkhar Avatar answered Feb 06 '23 15:02

Vishal Khakhkhar