AlarmManager & onStartCommand

£可爱£侵袭症+ 提交于 2019-12-04 20:22:43

I can see a number of issues here.

First, onStart(Intent intent, int startId) is deprecated, you don't need to implement this method (especially if all you do is super.onStart(intent, startId);).

Second, you don't need to cancel the repeating alarm before you set it, as the alarm manager will do that for you.

Most importantly, you should only acquire the wake lock for the duration of your onStartCommand method. Acquire it at the beginning, then release it at the end - ideally inside a finally block so that in the event of an exception the lock is still released. At the moment the lock is acquired the first time an intent is received, and then held until the service is terminated, preventing the CPU from hibernating when it has nothing to do - this will affect battery life.

As for repeated delivery of the intent - if your service variables are being re-initialised then it sounds like your service is being restarted by Android because it died. Have you checked in the logcat (when running connected) for any stack traces? Maybe add the process ID to your log output so you can spot when this is happening.

It is possible that Android is killing your service, if it thinks it has become unresponsive. You've put quite a bit of processing in, you might want to think about decomposing this into separate classes - then it will be easier to comprehend what the service is doing and where it is going wrong.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!