IntentService简介

IntentService简介

 

http://developer.android.com/reference/android/app/IntentService.html
http://android.tgbus.com/Android/tutorial/201106/355229.shtml
IntentService在处理事务时,还是采用的Handler方式,创建一个名叫ServiceHandler的内部Handler,并把它直接绑定到HandlerThread所对应的子线程。 
ServiceHandler把处理一个intent所对应的事务都封装到叫做onHandleIntent的虚函数;
因此我们直接实现虚函数onHandleIntent,再在里面根据Intent的不同进行不同的事务处理就可以了。
另外,IntentService默认实现了Onbind()方法,返回值为null。
  使用IntentService需要两个步骤:
  1、写构造函数
  2实现虚函数onHandleIntent,并在里面根据Intent的不同进行不同的事务处理就可以了。
好处:处理异步请求的时候可以减少写代码的工作量,比较轻松地实现项目的需求
实例1
MyIntentService.java文件
package com.lenovo.robin.test;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
 
public class MyIntentService extends IntentService {
final static String TAG="robin";
public MyIntentService() {
super("com.lenovo.robin.test.MyIntentService");
Log.i(TAG,this+" is constructed");
}
@Override
protected void onHandleIntent(Intent arg0) {
Log.i(TAG,"begin onHandleIntent() in "+this);
try {
Thread.sleep(10*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG,"end onHandleIntent() in "+this);
}
public void onDestroy()
{
super.onDestroy();
Log.i(TAG,this+" is destroy");
}
}
启动MyIntentServic的代码片段
Intent intent=new Intent(this,MyIntentService.class);
startService(intent);
startService(intent);
startService(intent);
AndroidManifest.xml文件代码片段

<service android:name=".MyIntentService" />

posted @ 2014-11-15 11:28  guoliuya  阅读(223)  评论(0编辑  收藏  举报