1.使用
public class CoreService extends IntentService {
String ex = "";
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
Toast.makeText(CoreService.this, "-e " + ex, Toast.LENGTH_LONG)
.show();
}
};
@Override
protected void onHandleIntent(Intent intent) {
// 耗时操作
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.sendEmptyMessage(0);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2.源码分析
IntentService == Service+HandlerThread(Thread+当前线程的Looper)+Handler(线程的Looper的Handler)
/**
* An abstract {@link Service} that serializes使连续 the handling of the Intents passed upon service
* start and handles them on a handler thread.
*/
public abstract class IntentService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private String mName;
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);
}
}
public IntentService(String name) {
super();
mName = name;
}
@Override
public void onCreate() {
super.onCreate();
// 创建一个线程,并且线程代码
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
// 利用HandlerThread的Looper创建对应线程的Handler,这样handler发送的Message就能发送到指定的Looper中
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
// 发送Message到ServiceLooper的MessageQueue中
mServiceHandler.sendMessage(msg);
}
// 线程中执行
protected abstract void onHandleIntent(Intent intent);
}
/**
* Handy方便的 class for starting a new thread that has a looper. The looper can then be
* used to create handler classes. Note that start() must still be called.
*/
public class HandlerThread extends Thread {
private int mPriority;
private int mTid = -1;
private Looper mLooper;
// 创建一个Looper,并且死循环查询当前线程的MessageQueue是否有Message
public void run() {
mTid = Process.myTid();
Looper.prepare();
mLooper = Looper.myLooper();
Looper.loop();
}
}
3.总结:
3.1 类之间关系
IntentService:引用HandlerThread和ServiceHandler
HandlerThread:引用Looper,线程中创建Looper和Looper.loop不断查询线程MessageQueue中是否有消息
ServiceHandler:handler的一个子类,handleMessage中回调onHandleIntent
3.2 两个引擎
E1:Service.onCreate:创建HandlerThread,并启动该线程(循环查询消息)
E2:Service.onStart使用HandlerThread的Looper创建Handler(ServiceHandler),并且发送消息给HandlerThread的Looper的消息队列
消息队列取出Handler(ServiceHandler)中的消息,并执行handlerMessage(线程中执行),此时回调onHandleIntent