1. 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(Intent, int)
方法中,调用ServiceHandler
的sendMessage(Message)
方法。
2. 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;
}
}
3. ServiceHandler类
ServiceHandler
继承了Handler
类,设置了looper
参数,所有的操作都会在该looper
线程中进行,也就是在HandlerThread
线程中进行。onHandleIntent(Intent)
方法实现了回调。
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);
}
}
4. 创建IntentService
如果我们需要一个下载文件Service
,DownloadService
继承IntentService
,只需要实现onHandleIntent(Intent)
方法即可。
public class DownloadService extends IntentService {
public DownloadService(String name) {
super(name);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
}
}
相关文章
Android Service简介
Android IntentService应用
Android Handler类
Android AsyncQueryHandler类