Android onHandleIntent与;启动命令
我目前正在编写一个android程序,它需要一个Android onHandleIntent与;启动命令,android,android-service,intentservice,Android,Android Service,Intentservice,我目前正在编写一个android程序,它需要一个IntentService。当我将代码放入onHandleIntent函数时,代码不会运行,但不会在main活动中给出错误。但是,当我将代码复制到onStartCommand中时,它运行得非常好 问题是我想知道onHandleIntent和onStartCommand之间有什么区别。谢谢 代码: 在OnHandleContent中: System.out.println("SERVICE STARTED! ! !"); //System.out.p
IntentService
。当我将代码放入onHandleIntent
函数时,代码不会运行,但不会在main活动中给出错误。但是,当我将代码复制到onStartCommand
中时,它运行得非常好
问题是我想知道onHandleIntent
和onStartCommand
之间有什么区别。谢谢
代码:
在OnHandleContent
中:
System.out.println("SERVICE STARTED! ! !");
//System.out.println(intent.getBooleanExtra("once", Boolean.FALSE));
if (intent.getBooleanExtra("once", Boolean.FALSE)) {
Check();
}
mHandler.postDelayed(mRunnable, 3000);
自:
IntentService
执行以下操作:
- 创建一个默认工作线程,该线程执行传递到应用程序主线程之外的
onStartCommand()
的所有意图
- 创建一个工作队列,一次将一个意图传递给您的
onHandleIntent()
实现,这样您就不必担心
多线程
- 在处理完所有启动请求后停止服务,因此您无需调用
stopSelf()
- 提供返回
null
的onBind()的默认实现
- 提供了
onStartCommand()
的默认实现,该实现将意向发送到工作队列,然后发送到您的onHandleIntent()
实施。
而且:
所有这些加起来就是一个事实,您需要做的就是实现
onHandleIntent()
完成客户提供的工作。(不过,你
还需要为服务提供一个小型构造函数。)
因此,IntentService
是一种具有这些特殊属性的“自定义”服务。因此没有必要重写onStartCommand()
,实际上,除非您使用常规服务
类,否则不应该这样做
IntentService
用法的一些示例:
Activity.java
Intent it = new Intent(getApplicationContext(), YourIntentService.class);
it.putExtra("Key", "Value");
startService(it);
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.
}
//...
}
YourIntentService.java
Intent it = new Intent(getApplicationContext(), YourIntentService.class);
it.putExtra("Key", "Value");
startService(it);
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.
}
//...
}
您还可以查看或获取有关服务
和IntentService
的更多信息
另外,请选中。onStartCommand()
在您使用服务时使用<使用IntentService
时,应改用code>onHandleIntent()
<代码>意向服务
扩展服务
。根据文件
“您不应该为您的应用程序重写此方法(onStartCommand
)
相反,重写onHandleIntent(Intent)
,而
当IntentService收到启动请求时,系统调用。“
如果您已经覆盖了onStartCommand()
,这可能就是您的onHandleIntent()
没有被调用的原因。您不应该覆盖onStartCommand()
您的IntentService
如果这样做,请确保返回super.onStartCommand()代码>因为这会将意图发送到工作队列,然后发送到您的onHandleIntent()
实现。哇,这是非常彻底的。回答得好!我已经看过了教程,它们很棒!但是问题是我没有覆盖onStartCommand
或onHandleIntent
?你在问题上说你覆盖了onStartCommand
,你不应该在IntentService
上这样做。改为使用onHandleIntent
,它会自动调用。不,我没有同时覆盖它们。因此,解决方案是我将代码放入onHandleIntent()
函数中,覆盖它,然后离开return Service.START\u在onStartCommand()
函数中选择code>,不要覆盖它。这是对的吗?事实上,如果您使用的是IntentService,您甚至不应该费心编写onStartCommand方法。将您的逻辑放在onHandleIntent中。如果您在使用IntentService
时重写onStartCommand()
,您将无法稍后调用onHandleIntent()
,除非onStartCommand()
的最后一行是返回super.onStartCommand(intent、flags、startId)
。