Chr*_*ium 13 android android-service intentservice
我目前正在编写一个需要的android程序IntentService.当我将代码放在onHandleIntent函数中时,代码不会运行,但它不会给出错误MainActivity.但是当我将代码复制到其中时onStartCommand,它运行得很好.
问题是我想知道onHandleIntent和之间有什么区别onStartCommand.谢谢.
码:
在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);
Run Code Online (Sandbox Code Playgroud)
Mau*_*ker 37
从文档来看:
将IntentService执行以下操作:
- 创建一个默认的工作线程,该线程执行所有交付的意图,以
onStartCommand()与应用程序的主线程分开.- 创建一个工作队列,一次将一个意图传递给您的
onHandleIntent()实现,因此您永远不必担心多线程.- 在处理完所有启动请求后停止服务,因此您永远不必打电话
stopSelf().- 提供
onBind()该返回的默认实现null.- 提供默认实现
onStartCommand(),将意图发送到工作队列,然后发送到您的onHandleIntent()实现.
并且:
所有这些使得您需要做的就是实现
onHandleIntent()客户端提供的工作.(但是,您还需要为服务提供一个小构造函数.)
所以a IntentService是Service具有这些特殊属性的"自定义" .所以没有必要覆盖onStartCommand(),实际上,除非你使用常规类,否则你不应该这样做Service.
一些IntentService使用示例:
Activity.java
Intent it = new Intent(getApplicationContext(), YourIntentService.class);
it.putExtra("Key", "Value");
startService(it);
Run Code Online (Sandbox Code Playgroud)
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.
}
//...
}
Run Code Online (Sandbox Code Playgroud)
您还可以查看本教程或这一个有关更多信息Service和IntentService.
另外,检查文档.
onStartCommand()当您使用Service. onHandleIntent()当您使用IntentService. IntentService延伸Service。根据文档
“您不应该
onStartCommand为您的 IntentService 重写此方法()。相反,应重写onHandleIntent(Intent),当 IntentService 收到启动请求时系统会调用该方法。”
如果您已覆盖onStartCommand(),这可能就是您onHandleIntent()没有被调用的原因。
| 归档时间: |
|
| 查看次数: |
11700 次 |
| 最近记录: |