首页 文章

对于IntentService,START_STICKY

提问于
浏览
5

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

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

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

有人可以帮我弄这个吗 ?

1 回答

  • 8

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

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

    只要你要求

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

    并在 IntentService 上使用正确的intent-filter:

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

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

    (唯一的例外是如果你的应用程序按照install location安装在SD卡上)

相关问题