Android HandlerThread 完全解析

来源:互联网 发布:小白鼠吃鸡软件 编辑:程序博客网 时间:2024/05/21 11:02
源码分析:
public class HandlerThread extends Thread {
    int mPriority;    int mTid = -1;    Looper mLooper;    public HandlerThread(String name) {        super(name);        mPriority = Process.THREAD_PRIORITY_DEFAULT;    }
总结:里面做了线程优先级的处理,主要是封装了looper,不用自己调用Looper的方法
场景:用于做完一件事,做另外一件事。

列子:用于下载应用,恢复下载的状态,handler.post()运作在工作线程中

private HandlerThread mHandlerThread = new HandlerThread("DownloadManager");
private DownloadManager(Context context) {    this.mContext = context.getApplicationContext();    downloadDbHelper = DownloadDbHelper.getInstance(context);    ApkHelper.getInstance(mContext).registListener(this);    mHandlerThread.start();    mHandler = new Handler(mHandlerThread.getLooper());}
/** 初始化下载列表 */    public void initDownloadTasks() {        mHandler.post(new Runnable() {            @Override            public void run() {                synchronized (TAG) {                    if (!isInitFinish.get()) {                        long startTime = System.currentTimeMillis();                        List<DownloadTask<BaseFileModel>> all = downloadDbHelper.queryAll();                        downloadTasks.clear();                        downloadTasks.addAll(all);                        restoreState();                        delFailureTimeTask();                        isInitFinish.set(true);                        CXLog.d(TAG, "use time---->" + (System.currentTimeMillis() - startTime));                        CXLog.d(TAG, "download size--->" + downloadTasks.size());                        //更多页面的游戏插件预下载//                        downLoadGameAppAll(mContext, instance);                    }                }            }        });    }

原创粉丝点击