Android Service学习之IntentService 深入分析
This "work queue processor" pattern is commonly used to offload tasks from an application‘s main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application‘s main loop), but only one request will be processed at a time.
private volatile Looper mServiceLooper; private volatile ServiceHandler mServiceHandler;
private String mName; private boolean mRedelivery;
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); }
}
下面是onCreate()的源码:
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.start();
mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); }
mServiceHandler.sendMessage(msg); }
通过对源码的分析得出: 这是一个基于消息的服务,每次启动该服务并不是马上处理你的工作,而是首先会创建对应的Looper,Handler并且在MessageQueue中添加的附带客户Intent的Message对象,当Looper发现有Message的时候接着得到Intent对象通过在onHandleIntent((Intent)msg.obj)中调用你的处理程序.处理完后即会停止自己的服务.意思是Intent的生命周期跟你的处理的任务是一致的.所以这个类用下载任务中非常好,下载任务结束后服务自身就会结束退出
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。