对于IntentService,START_STICKY

时间:2014-07-02 17:22:30

标签: android service android-service intentservice android-intentservice

我见过许多Android服务示例,其中返回START_STICKY用于启动应用程序,但无论如何我可以使用相同的IntentService。我知道Service方法在主UI线程和IntentService上作为单独的线程运行。

  1. 但是它们究竟是如何被调用的,为什么不能在启动时启动IntentService。由于IntentService在一个单独的线程上运行,如果我没有注意,我们可以更好地控制它。

  2. 我尝试在IntentService中使用onStartCommand,但我的应用程序在启动时崩溃,即使它在手动启动时工作正常。我们可以在IntentService中覆盖onStartCommand吗?

  3. 有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:8)

在启动时运行且START_STICKY与彼此无关 - START_STICKY是一个标志,用于确定如果您的服务被Android杀死会发生什么。

IntentService旨在处理传入的意图(通过handleIntent)并在之后立即停止。如source of IntentService所示,它已经恰当地处理onStartCommand

只要您要求

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

并在IntentService上使用正确的意图过滤器:

<intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
    <action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>

然后在启动完成后调用您的服务。

(例外情况是,如果您的应用按照install location安装在SD卡上)