您的位置:首页 > 其它

源码学习之IntenteService

2016-05-15 16:52 309 查看
IntentService是基于Service实现的,它会按需求处理一些异步任务。通过调用startService,客户端就可以发送请求了。如果有需要的话,Service才会被启动,在子线程依次处理每个Intent,处理完任务以后Service会停止。使用的时候要继承IntentService,并实现onHandleIntent(Intent intent)方法。IntentService会接收Intent,开启一个子线程,并在适当的时候停止Service。所有的请求会在一个单线程进行处理,所以在同一时刻只能处理一个任务。

调用onCreate以后,会启动一个工作线程(HandlerThread是继承Thread的),并初始化处理消息的ServiceHandler,和工作线程的Looper进行关联。
@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);
}


调用这个方法以后,会给mServiceHandler发送一条消息,任务交由mServiceHandler来处理。
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}


收到消息以后,会调用onHandleIntent方法,在这个方法里可以实现自己的逻辑处理。当处理完所有消息以后,会调用stopSelf来停止Service。
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: