一、IntentService诞生
我们在做产品需求的时候,经常需要在Service里做一些耗时操作(比如文件下载),而Service却是运行在主线程的,这时就需要我们自己去创建一个子线程和编写子线程相关的代码,这时你会不会想如果有人帮我把线程创建了该多好,这样只需要把精力放在业务相关的代码上,这多棒!!!现实中Google已经为我们考虑到这一点IntentService
就因此而诞生。
ps: IntentService
是继承自Service
,所以多次启动服务,同一时间也只会有一个IntentService
实例,但onStartCommand
会调用多次,同时不必担心多次调用onStartCommand
会覆盖掉之前执行的任务,因为IntentService
中维护一个消息列表MessageQueue
,而每个任务就是一个消息Message
。最后说一下,在所有消息执行完毕后,IntentService
会自动结束掉,不需要我们手动结束。
二、IntentService使用小例子
public class IntentServiceTest {
private static final String TAG = IntentServiceTest.class.getSimpleName();
private static final String TAGLife = IntentServiceTest.class.getSimpleName() + "—Life";
private static final String INTENT_KEY = "intent_key";
private Context mCtx;
public IntentServiceTest(Context context) {
mCtx = context;
}
public void excute() {
for (int i = 0; i < 5; i++) {
// 快速启动5次
Intent intent = new Intent(mCtx, MyIntentService.class);
intent.putExtra(INTENT_KEY, "intent" + i);
mCtx.startService(intent);
}
}
public static final class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAGLife, "MyIntentService -------------- onCreate()");
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
Log.d(TAGLife, "MyIntentService -------------- onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.d(TAGLife, "MyIntentService -------------- onDestroy()");
super.onDestroy();
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.d(TAG, "主线程id=" + Looper.getMainLooper().getThread().getId());
Log.d(TAG, "当前运行线程id=" + Thread.currentThread().getId());
try {
// 模拟耗时操作
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (intent != null) {
String value = intent.getStringExtra(INTENT_KEY);
Log.d(TAG, "intent_key=" + value + " threadId=" + Thread.currentThread().getId());
}
}
}
}
在上面的代码中,我们连续启动五次MyIntentService
,同时在MyIntentService
的onHandleIntent()
中让线程休息3秒钟,防止MyIntentService
在3秒内销毁,以测试多次start只创建一个实例,调用多次onStartCommand
。
别忘了maniofest中要注册下
<service android:name=".mj.IntentServiceTest$MyIntentService" />
运行结果:
02-08 18:53:11.557 19198-19198/com.ktln.must D/IntentServiceTest—Life: MyIntentService -------------- onCreate()
02-08 18:53:11.557 19198-19198/com.ktln.must D/IntentServiceTest—Life: MyIntentService -------------- onStartCommand()
02-08 18:53:11.557 19198-19198/com.ktln.must D/IntentServiceTest—Life: MyIntentService -------------- onStartCommand()
02-08 18:53:11.557 19198-19198/com.ktln.must D/IntentServiceTest—Life: MyIntentService -------------- onStartCommand()
02-08 18:53:11.557 19198-19198/com.ktln.must D/IntentServiceTest—Life: MyIntentService -------------- onStartCommand()
02-08 18:53:11.557 19198-19198/com.ktln.must D/IntentServiceTest—Life: MyIntentService -------------- onStartCommand()
02-08 18:53:11.567 19198-19216/com.ktln.must D/IntentServiceTest: 主线程id=1
02-08 18:53:11.567 19198-19216/com.ktln.must D/IntentServiceTest: 当前运行线程id=23182
02-08 18:53:14.567 19198-19216/com.ktln.must D/IntentServiceTest: intent_key=intent0 threadId=23182
02-08 18:53:14.567 19198-19216/com.ktln.must D/IntentServiceTest: 主线程id=1
02-08 18:53:14.567 19198-19216/com.ktln.must D/IntentServiceTest: 当前运行线程id=23182
02-08 18:53:17.567 19198-19216/com.ktln.must D/IntentServiceTest: intent_key=intent1 threadId=23182
02-08 18:53:17.567 19198-19216/com.ktln.must D/IntentServiceTest: 主线程id=1
02-08 18:53:17.567 19198-19216/com.ktln.must D/IntentServiceTest: 当前运行线程id=23182
02-08 18:53:20.567 19198-19216/com.ktln.must D/IntentServiceTest: intent_key=intent2 threadId=23182
02-08 18:53:20.567 19198-19216/com.ktln.must D/IntentServiceTest: 主线程id=1
02-08 18:53:20.567 19198-19216/com.ktln.must D/IntentServiceTest: 当前运行线程id=23182
02-08 18:53:23.567 19198-19216/com.ktln.must D/IntentServiceTest: intent_key=intent3 threadId=23182
02-08 18:53:23.567 19198-19216/com.ktln.must D/IntentServiceTest: 主线程id=1
02-08 18:53:23.567 19198-19216/com.ktln.must D/IntentServiceTest: 当前运行线程id=23182
02-08 18:53:26.567 19198-19216/com.ktln.must D/IntentServiceTest: intent_key=intent4 threadId=23182
02-08 18:53:26.567 19198-19198/com.ktln.must D/IntentServiceTest—Life: MyIntentService -------------- onDestroy()
三、IntentService源码分析
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper; // 内置消息队列,并提供消息循环遍历
private volatile ServiceHandler mServiceHandler; // 处理Looper中取出的消息
private String mName;
// IntentService意外中断后处理方式:
// true 返回 START_REDELIVER_INTENT,使用保留的Intent重启IntentService
// false 返回 START_NOT_STICKY , 不重启
private boolean mRedelivery;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public IntentService(String name) {
super();
mName = name;
}
/**
* Sets intent redelivery preferences. Usually called from the constructor
* with your preferred semantics.
*
* <p>If enabled is true,
* 如果设置为true
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_REDELIVER_INTENT}, so if this process dies before
* {@link #onHandleIntent(Intent)} returns, the process will be restarted
* and the intent redelivered.
* onStartCommand(Intent, int, int)方法返回START_REDELIVER_INTENT,因此当Service在执行
* onHandleIntent(Intent)之前挂掉,则线程会使用最近发送的Intent,来重新启动Service
* If multiple Intents have been sent, only the most recent one is guaranteed to be redelivered.
* 如果发生了多个Intent,只有最后一个才能被重新发送。
*
* <p>If enabled is false (the default),
* 如果设置为false
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
* dies along with it.
* onStartCommand(Intent, int, int)方法返回START_NOT_STICKY,
* 并且如果Service挂掉,Intent也同样会被回收
*/
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
@Override
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
// 创建一个HandlerThread对象,HandlerThread调用start方法后,会帮助我们创建一个Looper对象
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
// 获得HandlerThread中的Looper对象
mServiceLooper = thread.getLooper();
// 使用HandlerThread的Looper对象,构建一个Handler,这个Handler是运行在子线程中(即HandlerThread)
mServiceHandler = new ServiceHandler(mServiceLooper);
}
// 废弃方法,现在使用onStartCommand来替代
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
/**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see android.app.Service#onStartCommand
*/
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId); // startId系统生成的,可以理解为对当前Intent的标记
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
// 销毁时,释放Looper的资源
mServiceLooper.quit();
}
/**
* Unless you provide binding for your service, you don't need to implement this
* method, because the default implementation returns null.
* @see android.app.Service#onBind
*/
@Override
@Nullable
public IBinder onBind(Intent intent) {
return null;
}
/**
* This method is invoked on the worker thread with a request to process.
* Only one Intent is processed at a time, but the processing happens on a
* worker thread that runs independently from other application logic.
* So, if this code takes a long time, it will hold up other requests to
* the same IntentService, but it will not hold up anything else.
* When all requests have been handled, the IntentService stops itself,
* so you should not call {@link #stopSelf}.
*
* @param intent The value passed to {@link
* android.content.Context#startService(Intent)}.
* This may be null if the service is being restarted after
* its process has gone away; see
* {@link android.app.Service#onStartCommand}
* for details.
*/
@WorkerThread
protected abstract void onHandleIntent(@Nullable Intent intent); // 处理耗时操作,运行在工作线程(即:子线程)
}
代码分析都已经放到源码注释上了,直接看源码就好。IntentService
的源码比较简单,主要是对HandlerThread
的使用,不熟悉HandlerThread
的可以看我的这篇文章【HandlerThread源码分析】,这里额外提一下stopSelf(msg.arg1);
调用此方法并不一定会停止Service,具体源码可以看这篇文章【详细剖析IntentService的运作机理】
顺便给一下Android中framework层源码下载地址,方便小伙伴们学习
github: https://github.com/android/platform_frameworks_base
google 官方: https://android.googlesource.com/platform/frameworks/base.git
网友评论