简体   繁体   English

长时间运行的后台任务,Android

[英]Long running background task, Android

I am parsing all text messages from the device and extracting words from them. 我正在解析设备中的所有短信,并从中提取单词。 For doing this I first used Service , but the issue with it was that it made application slower or sometimes I got notification that Application is taking longer to run. 为此,我首先使用Service ,但是问题在于它使应用程序变慢,或者有时我收到通知,指出应用程序需要更长的运行时间。 Alternative to this I used IntentService . 作为替代方案,我使用了IntentService But problem with intent service is that whenever I stopped the application, I couldn't see my service running anymore. 但是意图服务的问题是,每当我停止应用程序时,我就看不到我的服务在运行。 Alongside I also have to use Alarm Manager to schedule the things. 另外,我还必须使用“警报管理器”来安排事情。 I am planning to use SyncAdapter for doing both of the things, but I don't think it would be a good option to use it. 我打算使用SyncAdapter来完成这两项工作,但是我认为使用它不是一个好选择。 It would be really helpful if there is a better possible for doing this. 如果有更好的方法可以这样做,将非常有帮助。

Background task might take upto 5-10 minutes for completion and I am planning to run it in every 12 hours. 后台任务最多可能需要5-10分钟才能完成,因此我计划每12小时运行一次。 Though I won't be parsing old messages again. 虽然我不会再解析旧消息。 So it won't take longer after first time. 因此,第一次之后就不需要更长的时间了。 The task should not end even when application is closed. 即使关闭了应用程序,该任务也不应结束。

Basically IntentService is apt for background tasks which are not tied to the application lifecycle. 基本上, IntentService适用于与应用程序生命周期IntentService的后台任务。

But problem with intent service is that whenever I stopped the application, I couldn't see my service running anymore. 但是意图服务的问题是,每当我停止应用程序时,我就看不到我的服务在运行。

You can send updates to UI from intent service by using: 您可以使用以下方法从意图服务向UI发送更新:

LocalBroadcastManager : how to use LocalBroadcastManager? LocalBroadcastManager如何使用LocalBroadcastManager?

Handler : How to Collect info from IntentService and Update Android UI Handler如何从IntentService收集信息并更新Android UI

Also you might want to see this video: The Zen of IntentService. 您可能也想看以下视频: IntentService的Zen。 (Android Performance Patterns) (Android性能模式)

EDIT : 编辑
Forget about using IntentService , it stops as the app stops because it runs on the same process as the app. IntentService使用IntentService ,它会在应用程序停止时停止运行,因为它与应用程序在同一进程上运行。

Since you want your service to work as a job every 12 hours, you could use a 'Scheduled Service'. 由于您希望您的服务每12个小时工作一次,因此可以使用“计划的服务”。 You can use JobScheduler or Firebase JobDispatcher API 您可以使用JobSchedulerFirebase JobDispatcher API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM