android - 使用定时器重复 IntentService - 是否可取?

标签 android android-alarms android-intentservice

我有一个从服务器下载数据的 IntentService,我希望 IntentService 在特定时间间隔检查服务器更新。然而,以下帖子建议不要使用 Timer 重复 Service - 而是强调使用 AlarmManager:

Why doesn't my Service work in Android? (I just want to log something ever 5 seconds)

Android - Service: Repeats only once

Android service stops

在 Android 的引用手册中,IntentService 被描述为:

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

我不太明白的部分是为什么 IntentService(帖子中的问题是针对 Service 而不是 IntentService) 不允许使用 Timer 重复执行,因为它会创建自己的工作线程来执行。是否允许在 IntentService 中使用 Timer ?还是 AlarmManagers 是定期执行 IntentService 的唯一解决方案?

对此的解释将不胜感激。

最佳答案

Or are AlarmManagers the only solution to periodically execute an IntentService ?

如果您希望它可靠地工作,可以。使用 AlarmManager 对用户也更加友好。

首先,不要让任何形式的服务运行,主动向以下对象交付值(value)时除外用户。看着时钟滴答作响并没有积极地向用户传递值。运行 Service 使您的进程比其他进程具有更高的优先级,即哪些进程被终止以释放系统 RAM 以供将来工作使用。不必要地使用 Service(例如简单地看时钟滴答声)会妨碍用户处理多项任务的能力,因为您不必要地占用了系统 RAM。

此行为会导致某些用户使用任务 killer 攻击您,例如将您的应用从最近任务列表中删除。这将终止您的进程,因此您的 Timer 也会消失。同样,由于太多草率的开发人员长期保留他们的Service,Android 会在一段时间后自动终止此类进程,尽管有Service

最后,通常“以特定时间间隔检查服务器更新”的一个方面是您希望即使设备进入休眠模式也能进行这项工作。使用永久服务方法,这将要求您使用 WakeLock 始终保持 CPU 开启。这将显着影响用户的电池,导致您的应用出现在“设置”应用的“电池故障屏幕”上。这与 bundle 系统 RAM“功能”相结合,可能会导致您的应用获得一些较差的评级。

相反,通过使用 AlarmManager:

  • 您的 IntentService 只需要在执行其工作(“检查服务器更新”)时运行,在这些事件之间消失,因此您的进程可以终止以释放为用户正在做的其他事情增加系统 RAM

  • 通过使用 WakefulBroadcastReceiverWakefulIntentService 模式,您可以短暂唤醒设备来完成这项工作,然后让设备再次进入休眠状态,从而最大限度地减少对电池的影响

关于android - 使用定时器重复 IntentService - 是否可取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24241804/

相关文章:

java - 错误 :Internal error: (java. lang.NoSuchMethodError)影响我所有的项目

android - 无法从youtube/Android APi获取视频演示列表 Activity 功能以与测试应用程序集成-帮助确实需要

android - IntentService 的 onHandleIntent(Intent) 获取空参数

android - 使用 RxJava2 定期发送相同的请求

android - 用于 ListView 的 Google Now 卡片 UI

java - 如何在 Android 4.4 中设置准确的重复闹钟?

android - 创建带警报的重复服务

java - 从 DatePicker 和 TimePicker 设置 AlarmManager

android - IntentService (kotlin) 的默认构造函数

android - IntentService 不会与 PendingIntent 一起调用