开发者

Run a service in the background forever..? Android

开发者 https://www.devze.com 2022-12-20 21:40 出处:网络
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.

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 u开发者_Python百科se 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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号