Android onHandleIntent 和 onStartCommand 的区别

Android the difference between onHandleIntent & onStartCommand

我目前正在编写一个需要 IntentService 的 android 程序。当我把代码放在 onHandleIntent 函数中时,代码不会 运行,但它不会在 MainActivity 中给出错误。但是当我将我的代码复制到 onStartCommand 时,它 运行 是完美的。

问题是我想知道 onHandleIntentonStartCommand 之间有什么区别。谢谢。

代码:

onHandleIntent中:

System.out.println("SERVICE STARTED! ! !");
//System.out.println(intent.getBooleanExtra("once", Boolean.FALSE));
if (intent.getBooleanExtra("once", Boolean.FALSE)) {
    Check();
}
mHandler.postDelayed(mRunnable, 3000);

the docs开始:

IntentService 执行以下操作:

  • Creates a default worker thread that executes all intents delivered to onStartCommand() separate from your application's main thread.
  • Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multi-threading.
  • Stops the service after all start requests have been handled, so you never have to call stopSelf().
  • Provides default implementation of onBind() that returns null.
  • Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent() implementation.

还有:

All this adds up to the fact that all you need to do is implement onHandleIntent() to do the work provided by the client. (Though, you also need to provide a small constructor for the service.)

所以 IntentService 是具有这些特殊属性的 "Custom" Service。所以没有必要覆盖 onStartCommand(),实际上,你不应该这样做,除非你使用常规 Service class。

IntentService 用法的一些示例:

Activity.java

Intent it = new Intent(getApplicationContext(), YourIntentService.class);
it.putExtra("Key", "Value");
startService(it);

YourIntentService.java

public YourIntentService() {
    super("YourIntentService");
}

@Override
protected void onHandleIntent(Intent intent) {

    if (intent != null) {
        String str = intent.getStringExtra("key");
        // Do whatever you need to do here.
    }
    //...
}

您还可以查看 this tutorial or this one 了解有关 ServiceIntentService 的更多信息。

此外,检查 the docs

onStartCommand() 用于 Service。当您使用 IntentService 时,应使用 onHandleIntent()IntentService 扩展 Service。根据文档

"You should not override this method(onStartCommand) for your IntentService. Instead, override onHandleIntent(Intent), which the system calls when the IntentService receives a start request."

如果您覆盖了 onStartCommand(),这可能就是您的 onHandleIntent() 没有被调用的原因。

您不应该为您的 IntentService 覆盖 onStartCommand()

如果这样做,请确保 return super.onStartCommand();,因为这会将 Intent 发送到工作队列,然后发送到您的 onHandleIntent() 实施。