Android onHandleIntent 和 onStartCommand 的区别

标签 android android-service intentservice

我目前正在编写一个需要 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 是具有这些特殊属性的“自定义”服务。所以没有必要覆盖 onStartCommand(),实际上,您不应该这样做,除非您使用的是常规 Service 类。

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 tutorialthis one有关 ServiceIntentService 的更多信息。

另外,检查 the docs .

关于Android onHandleIntent 和 onStartCommand 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34646688/

相关文章:

android - 无法从小部件发送挂起的 Intent ,SendIntentException

android - 如何将数据传递给服务启动的 Activity

android - 在android中使用MVP模式时,android服务调用和对GoogleAPIClient的调用应该写在哪里?

android - Android 操作系统会在正常情况下杀死我的 IntentService 吗?

android - 使用 Retrofit2 和 rxJava2 处理没有主体的响应

android - 实现自定义 Android 的 libaudio.so 或 "how does audio work on Android?"

android - IntentService 和线程池

android - 在后台持续监听 Android 设备上的指纹

android -/sdcard上的音乐文件是否进入apk?

android - 根据 Activity 的广播接收器更新 fragment ui