IntentService应用
IntentService继承Service,但又不同于普通的Service。
Service是用于后台服务的,但它仍然在主线程中运行,耗时的逻辑和操作都不适合在Service中运行,IntentService弥补了这一缺点。
IntentService源码,
public abstract class IntentService extends Service {
@Override
public void onCreate() {
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);
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
}
在onCreeate()
方法中,创建了一个HandlerThread线程,并初始化了一个ServiceHandler来传递消息。
在onStart()
方法中,调用ServiceHandler的sendMessage()
方法。
HandlerThread类
HandlerThread是一个线程类,并在内部创建了一个Looper来管理线程。
public class HandlerThread extends Thread {
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason isAlive() returns false, this method will return null. If this thread
* has been started, this method will block until the looper has been initialized.
* @return The looper.
*/
public Looper getLooper() {
if (!isAlive()) {
return null;
}
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
}
ServiceHandler类
ServiceHandler继承了Handler类,设置了looper参数,所有的操作都会在该looper线程中进行,也就是在HandlerThread线程中进行。onHandleIntent()
方法实现了回调。
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);
}
}
创建IntentService
如果我们需要一个下载文件Service,DownloadService继承IntentService,只需要实现onHandleIntent()
方法即可。
public class DownloadService extends IntentService {
public DownloadService(String name) {
super(name);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
}
}