IntentService使用
来源:互联网 发布:久其软件财务报表 编辑:程序博客网 时间:2024/06/08 20:09
看IntentService源码,在onCreate方法
@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); }
创建了一个HandlerThread,称为work thread,再看HandlerThread的run方法
public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; }
通过其run方法可以看出HandlerThread已经是一个异步消息处理线程了。
ServiceHandler是用来往HandlerThread的消息队列中发送消息,并用来处理消息
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); } }
再看onStart方法
public void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); }
当startService(intent)开启服务,传来intent后,在onStart方法中,通过ServiceHandler传给HandlerThread所拥有的消息队列,然后HandlerThread取出该消息,调用ServiceHandler的handleMessage方法,在handleMessage方法中,ServiceHandler调用onHandleIntent((Intent)msg.obj)方法。
Service,IntentService,AsyncTask比较
Service用来处理耗时任务,可以常驻后台运行。
IntentService是Service的子类,它的特点是可以用来处理异步任务,当然该任务可以是耗时任务,而且可以处理多个异步任务,单同时只能处理一个,因为只有一个work thread,当处理完任务后,自己会停止。
AsyncTask也可以用来处理耗时任务,它的好处是和Ui线程交互起来很方便,不同的方法工作在不同的线程中,方法的执行顺序是规定好的。
0 0
- 使用IntentService
- IntentService使用
- IntentService使用
- IntentService使用
- IntentService 使用
- IntentService的使用
- intentservice 简单使用
- 使用后台服务 IntentService
- Android:IntentService的使用
- Android IntentService 的使用
- 【安卓篇】IntentService的使用
- android IntentService使用
- IntentService的使用
- IntentService简介及其使用
- IntentService 的使用
- Android IntentService的使用
- 一个IntentService使用实例
- IntentService介绍及使用
- [Mac] Mac book pro换SSD硬盘、制作启动U盘、TimeMachine恢复 小记
- JMeter中对于Json数据的处理方法
- POJ - 3273 Monthly Expense
- Codeforces 439B Devu, the Dumb Guy(贪心)
- Toast 文本显示
- IntentService使用
- VS2005无法启动调试
- 九度 题目1183:守形数
- 【剑指offer】面试题12:打印1到最大的n位数
- hdu1518 Square
- Android Camera(一)
- Web服务器管理系列:5、利用MSConfig排查木马
- 开始了
- SSH执行流程