Android Developer - Alarm manager vs service

巧了我就是萌 提交于 2019-12-09 17:10:40

问题


I am making an app that needs to execute a function each hour even the app is closed.

First of all, I thought to create a service, but during my tests, I realise that android sometimes kills my service. So I was looking for another solution and I found AlarmManager. I have implemented it and it seems to work but I have the doubt if it will happen the same the service or it will run forever? (Until reboot of the mobile...)

Another question, it is necessary to create a new thread to execute the process in alarm manager or it runs directly in other thread?


回答1:


I have implemented it and it seems to work but I have the doubt if it will happen the same the service or it will run forever? (Until reboot of the mobile...)

It will run until:

  • the device is rebooted, as you noted, or
  • the user uninstalls your app, or
  • you cancel the events yourself, or
  • the user goes into Settings, finds your app in the list of installed apps, taps on that entry, and clicks the Force Stop button

It's possible that alarms will need to be scheduled again after your app is upgraded (I forget...).

it is necessary to create a new thread to execute the process in alarm manager or it runs directly in other thread??

Unless the work you are going to do will take only a couple of milliseconds, you will want a background thread for it. That leads to two possible patterns:

  1. If you are not using a _WAKEUP-style alarm, use a getService() PendingIntent to send control to an IntentService every hour

  2. If you are using a _WAKEUP-style alarm, you will need to use a getBroadcast() PendingIntent, and have it either invoke your subclass of my WakefulIntentService, or you will need to manage a WakeLock yourself to keep the device awake while you do your bit of work




回答2:


No, Android won't kill scheduled alarms and they got executed as planned unless app is replaced or device is rebooted. Use broadcast receivers for these events to reschedule Alarms. There's no way to prevent Force Stop as it kills all of your app components and threads totally.

That depends on what Alarm Manager do. If it sends a broadcast, the receiver limit is 10 second.

If it starts an Activity, Service or Intent Service, there is no limit. For Activity and Services you must finish or stop it and for Intent Services until the process is finished. Be aware that you can't have another thread inside Intent Service and you'r limited to code inside the OnHandleIntent.

Also you must consider device state. If it's sleep and you are using Wake Up flag receivers won't need a wake lock, but others do. It won't take long for device to go back to sleep.

Don't waste system resources with a service because Alarm Manager do what you want.



来源:https://stackoverflow.com/questions/16158086/android-developer-alarm-manager-vs-service

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