运行 IntentService 最多一次
run an IntentService at most once
我有一个 IntentService
,我希望 startCommand
仅在尚未 运行.
时被调用
这是因为此服务正在处理数据库中的所有现有行。它可以被调用多次启动,但如果它已经 运行 它不应该再次启动。并且类似于IntentService
没有要处理的行后,它应该自行关闭。
这可以实现吗?也许 PendingIntent
和 FLAG_NO_CREATE
?
我可以用 Service
和一个单独的线程而不是 IntentService
创建它,但是 IntentService
已经实现了线程。
Maybe with PendingIntent and FLAG_NO_CREATE ?
该标志是指创建 PendingIntent
,而不是服务。
Is this achievable?
现成的:
第 1 步:在您的服务中,添加一个 AtomicBoolean
字段(此处称为 isRunning
),初始设置为 false
.
步骤 #2:覆盖 onStartCommand()
。如果 isRunning
是 false
,将其设置为 true
并链接到 super.onStartCommand()
以继承正常的 IntentService
行为。如果 isRunning
是 true
,不要链接到 super.onStartCommand()
。
第 3 步:在 onHandleIntent()
中,将所有工作包装在 try
/finally
块中,您将 isRunning
设置为 false
finally
.
Net:如果 onHandleIntent()
尚未 运行。
,则 startService()
调用只会经过正常的 IntentService
处理
我有一个 IntentService
,我希望 startCommand
仅在尚未 运行.
这是因为此服务正在处理数据库中的所有现有行。它可以被调用多次启动,但如果它已经 运行 它不应该再次启动。并且类似于IntentService
没有要处理的行后,它应该自行关闭。
这可以实现吗?也许 PendingIntent
和 FLAG_NO_CREATE
?
我可以用 Service
和一个单独的线程而不是 IntentService
创建它,但是 IntentService
已经实现了线程。
Maybe with PendingIntent and FLAG_NO_CREATE ?
该标志是指创建 PendingIntent
,而不是服务。
Is this achievable?
现成的:
第 1 步:在您的服务中,添加一个 AtomicBoolean
字段(此处称为 isRunning
),初始设置为 false
.
步骤 #2:覆盖 onStartCommand()
。如果 isRunning
是 false
,将其设置为 true
并链接到 super.onStartCommand()
以继承正常的 IntentService
行为。如果 isRunning
是 true
,不要链接到 super.onStartCommand()
。
第 3 步:在 onHandleIntent()
中,将所有工作包装在 try
/finally
块中,您将 isRunning
设置为 false
finally
.
Net:如果 onHandleIntent()
尚未 运行。
startService()
调用只会经过正常的 IntentService
处理