一、servicer:用于处理后台的一些耗时任务(不是运行在独立的线程)
1、service的启动方式:(startService和bindService)
? ? ? ? startService:
? ? ? ?a、?生命周期:onCreate()只执行一次;onStartCommand()跟随startService()的调用次数而定。
public void onCreate() {
}
public @StartResult int onStartCommand(Intent intent, @StartArgFlags int flags, int startId) {
onStart(intent, startId);
return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;
}
public void onDestroy() {
}
? ? ? ? b、startService的启动方式:service需要手动调用stopSelf()方法或者stopService()方法,才会停止运行并且销毁;
? ? ? ? bindService:
? ? ? ? 生命周期:onCreate()只执行一次;onBind()跟随startService()的调用次数而定。
public void onCreate() {
}
public abstract IBinder onBind(Intent intent);
public void onDestroy() {
}
????????? b、bindService的启动方式:service在不手动调用unBindService()方法的时候,随绑定的组件(比如:activity)销毁而销毁。
二、intentService:相对于service有以下3点优点
1、可以处理后台耗时的任务,并且在任务执行完后会自动停止
原因:在intentService的onCreate()方法中,创建了一个子线程HandlerThread,并且通过thread.getLooper()拿到这个线程的Looper,用这个looper创建了一个ServiceHandler;在onStart()方法中,通过handler.sendMessage()发送消息;在ServiceHandler的handleMessage方法里调用了onHandleIntent()方法;随后又调用了stopSelf()方法;
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);
}
}
@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 thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
2、具有高优先级,并且不容易被系统杀死
原因:在handlerThread的构造方法中,设置了线程的优先级为高等级(mPriority = Process.THREAD_PRIORITY_DEFAULT(==0))
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
/**
* Standard priority of application threads.
* Use with {@link #setThreadPriority(int)} and
* {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
* {@link java.lang.Thread} class.
*/
public static final int THREAD_PRIORITY_DEFAULT = 0;
3、可以多次启动,每个耗时操作都会以工作队列的方式在intentService的onHandleIntent()回调方法中执行
原因:因为每个任务都是以消息的形式在Handler中运行,Handler的MessageQueue本身就是一个单链表实现的优先级队列。
|