Android - 运行 一个 IntentService 多次

Android - Running a IntentService multiple times

所以我有一个 IntentService 当我 运行 它一次时 运行 没问题。它对图像进行处理,然后输出一系列 RGB 值。

但我现在需要它做的是 运行 多次以批处理出一系列图像。我的第一次尝试是在我的主 class 中调用停止服务,然后创建并 运行 一个新的 IntentService 实例。但是当我调用 StopService 时这崩溃了。

有正确的方法吗?

IntentService 在处理完所有请求后停止服务,因此您永远不必调用 stopSelf()

IntentService 不能运行 并行任务,所有连续的意图将进入消息队列并按顺序执行。

因此,只需将它们一个接一个地添加,并确保 clean-up 您的字段以确保独立处理所有 Intent,因为不会重新创建 IntentService object/thread。

关于意向服务你必须知道的:

"The IntentService class provides a straightforward structure for running an operation on a single background thread. This allows it to handle long-running operations without affecting your user interface's responsiveness. "

不要实现 onStartCommand 方法,因为如果你这样做,你必须在完成时调用 stopSelf() 或 stopService()。如果您不覆盖此方法,那么 Android OS 会处理所有事情。

正如@Radu Ionescu 所提到的,intentService 停止工作, 当它完成所有到达它的 onHandleIntent 方法的请求时。

IntentService 在打开时创建一个默认工作线程,并执行到达 onHandleIntent 方法的所有内容。

只需将所有内容添加到它的队列中,或者如果您需要花费更长的时间才能添加两个不同的操作,您可以使用 Service,以防止 IntentService 自我破坏。