我目前正在编写一个需要IntentService
的android程序。当我将代码放入onHandleIntent
函数时,代码不会运行,但它不会在MainActivity
中给出错误。但是,当我将代码复制到onStartCommand
时,它运行得非常完美。
问题在于我想知道onHandleIntent
和onStartCommand
之间的区别。感谢。
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);
答案 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 tutorial或this one,了解有关Service
和IntentService
的更多信息。
另外,请检查the docs。
答案 1 :(得分:4)
onStartCommand()
时会使用 Service
。使用onHandleIntent()
时,应使用IntentService
。 IntentService
延伸Service
。并根据文件
&#34;您不应该为您的方法覆盖此方法(
onStartCommand
) IntentService。相反,覆盖onHandleIntent(Intent)
,其中 当IntentService收到启动请求时系统调用。&#34;
如果您覆盖了onStartCommand()
,那么这可能就是您onHandleIntent()
未被调用的原因。
答案 2 :(得分:2)
您不应为onStartCommand()
覆盖IntentService
。
如果您这样做,请务必return super.onStartCommand();
,因为这会将Intent
发送到工作队列,然后发送到onHandleIntent()
实施。