Android onHandleIntent&的区别onStartCommand

时间:2016-01-07 02:59:02

标签: android android-service intentservice

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

问题在于我想知道onHandleIntentonStartCommand之间的区别。感谢。

CODE:

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);

3 个答案:

答案 0 :(得分:34)

the docs开始:

IntentService执行以下操作:

  
      
  • 创建一个默认工作线程,该线程执行与应用程序主线程分开的所有传递到onStartCommand()的意图。
  •   
  • 创建一个工作队列,一次将一个意图传递给onHandleIntent()实现,因此您永远不必担心   多线程。
  •   
  • 处理完所有启动请求后停止服务,因此您无需致电stopSelf()
  •   
  • 提供onBind()的默认实现,返回null
  •   
  • 提供onStartCommand()的默认实施,将意图发送到工作队列,然后发送到onHandleIntent()   实施
  •   

还有:

  

所有这些都使您需要做的就是实施   onHandleIntent()来完成客户提供的工作。 (虽然,你   还需要为服务提供一个小的构造函数。)

所以IntentService是"自定义" Service具有这些特殊属性。因此,除非您使用常规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

答案 1 :(得分:4)

使用onStartCommand()时会使用

Service。使用onHandleIntent()时,应使用IntentServiceIntentService延伸Service。并根据文件

  

&#34;您不应该为您的方法覆盖此方法(onStartCommand)   IntentService。相反,覆盖onHandleIntent(Intent),其中   当IntentService收到启动请求时系统调用。&#34;

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

答案 2 :(得分:2)

您不应为onStartCommand()覆盖IntentService

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