Android因长期运行问题导致ANR消息
我的问题一般是 - 如何让后台服务在每个“间隔”运行并且不收到 ANR 消息(尝试创建一个从 AlarmManager 调用的服务,该服务启动一个线程来完成其工作)? 感谢您的帮助!
更具体地说:
我正在制作一个类似于 DropBox 的应用程序 - 使本地文件夹与其他 Android 手机共享。
该应用程序应在后台运行。
它还应该以一定的时间间隔运行,以检查本地目录中是否创建了任何新数据,以便将其上传到某个服务器。
我的应用程序通常会执行 PsudoCode 中的下一个序列:
1) AlarmManager.setInexactRepeating(MySerVice)
2) (when the service is being called) DecideWhichFileToUploadOrDownload()
3) UploadNewFiles() DownloadNewFiles()
我知道问题出在第 3 阶段,在上传/下载花费超过 10 秒后,我收到 ANR 消息(或者我的应用程序被终止),如果上传/下载时间不到 10 秒,一切正常。 我试图创建一个线程来执行上传/下载,但是一旦服务完成,Android 就会杀死我的线程。
My question in general is - how to make a background service run every "INTERVAL" and not get the ANR message(Tried making a service called from alarmManager which initiate a thread to do its job)?
Thanks for any help!
More specific:
I am making an application which is kind of DropBox - make a local folder be shared with other Android phones.
This application should run in the background.
It also should run in some time intervals in order to check if any new data created in the local directory in order to upload it to some server.
My application in general does the next sequence in PsudoCode :
1) AlarmManager.setInexactRepeating(MySerVice)
2) (when the service is being called) DecideWhichFileToUploadOrDownload()
3) UploadNewFiles() DownloadNewFiles()
I know that the problem is with stage 3, after a upload/download that takes more than 10 seconds i get the ANR message (or my application is being killed), if the upload/download is shorter than 10 seconds than all works just fine.
I tried to make a thread that will do the upload/download but once the Service is finished Android kill my Thread.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
IntentService
,以便在后台线程上完成工作。这就是为什么您应该使用
IntentService
,因为 Android 会为您管理后台线程并停止Service
。您只需通过startService()
向其发送工作,并在onHandleIntent()
中完成工作。Use an
IntentService
, so that the work is done on a background thread.Which is why you should use an
IntentService
, as Android manages both the background thread and stopping theService
for you. You just send it work viastartService()
and do the work inonHandleIntent()
.不要忘记,当您的服务(由 Alarm 服务调用)执行可能需要长时间运行和/或异步的操作时,您必须考虑使用 IntentService 或您自己的线程消息传递服务
,并且
WakeLock(请参阅 PowerManager),
否则设备可能返回/进入“深度睡眠”状态。然后 CPU 状态将被冻结,直到下一个“事件”
尽快在您的服务中获取 WakeLock,并确保在后台工作结束时释放它......
Do not forget that when your service (invoked by Alarm service) do thing that may required long run execution and/or asynchronous youve to think to use IntentService or you own thread messaging service
and
WakeLock (see PowerManager)
otherwise the device may return/go to "deep sleep" state.. Then CPU state is fronzen until next "event"
Acquire WakeLock ASAP in your service and be sure to release it at the end of your background work...