转载请注明出处:http://blog.csdn.net/llew2011/article/details/51373243
提起Service大家都很熟悉,它乃Android四(si)大(da)组(jing)件(gang)之一。但是说起IntentService有童靴或许有点陌生,看名字感觉和Service有关连。不错,不仅有关联而且关系还不一般,IntentService是Service的子类,所以它也是正宗的Service,由于IntentService借助了HandlerThread,我们今天就从源码的角度巴拉一下IntentService及HandlerThread,看看它们是何方神圣,如果你对它们非常熟悉,请跳过本文(*^__^*) ……
开始巴拉IntentService源码之前我们先看看它的基本用法,既然IntentService是正宗的Service,那它的用法就和Service一样。IntentService也是一个抽象类,需要实现其抽象方法onHandleIntent()。我们先定义BackgroundService,使之继承IntentService并实现其抽象方法onHandleIntent(),然后重写IntentService的生命周期方法并打印日志,代码如下:
public class BackgroundService extends IntentService {
private static final String TAG = BackgroundService.class.getSimpleName();
public BackgroundService() {
super("TT");
Log.e(TAG, "BackgroundService() " + Thread.currentThread());
}
@Override
public void onCreate() {
Log.e(TAG, "onCreate() " + Thread.currentThread());
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
Log.e(TAG, "onStart() " + Thread.currentThread());
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand() " + Thread.currentThread());
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e(TAG, "onDestroy() " + Thread.currentThread());
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "onBind() " + Thread.currentThread());
return super.onBind(intent);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.e(TAG, "onHandleIntent() " + Thread.currentThread());
}
}
我们在重写的部分方法中添加了日志,主要打印当前方法名和方法执行时所在的线程名称。然后在配置文件manifest.xml中配置BackgroundService,代码如下:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.llew.wb.source.intentservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.llew.wb.source.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.llew.wb.source.BackgroundService" >
</service>
</application>
</manifest>