重温HandlerThread

这个大家一点儿都不陌生,今天在复习的时候简单写了一个demo,简单记录下,方便以后复习。
这里主要是模拟下载实现,用两种方式实现,对比学习HandlerThread。下面上代码:
///////HandlerThreadActivity.java

/**
 * create by xiaoya on 2019-12-04
 * des:模拟下载使用HandlerThread的demo;
 **/
public class HandlerThreadActivity extends Activity implements View.OnClickListener, Handler.Callback {

    /**
     * 我是按钮
     */
    private TextView mTvBtn;
    private Handler handler;
    private DownLoadThread handlerThread;
    private MyHandlerThread myHandlerThread;
    /**
     * 开始下载
     */
    private TextView mTvStart;
    /**
     * 完成下载
     */
    private TextView mTvFinish;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handlerthread);
        initView();
        //使用系统的HandlerThread
//        initHandlerThread();
        //使用自己实现的Handler+Thread;
        initMyHandlerThread();


    }
    private void initHandlerThread(){
        handler = new Handler(this);
        handlerThread = new DownLoadThread("logReapt");
        handlerThread.setUiHandler(handler);
        handlerThread.setUrlLists("qqqqqq", "qqwwwwww", "errtttttt", "jjjjjjjjjjjj");
    }

    private void initMyHandlerThread(){
        handler = new Handler(this);
        myHandlerThread = new MyHandlerThread("logReapt");
        myHandlerThread.setUiHandler(handler);
        myHandlerThread.setUrlLists("qqqqqq", "qqwwwwww", "errtttttt", "jjjjjjjjjjjj");
    }

    private void initView() {
        mTvBtn = (TextView) findViewById(R.id.tv_btn);
        mTvBtn.setOnClickListener(this);
        mTvStart = (TextView) findViewById(R.id.tv_start);
        mTvFinish = (TextView) findViewById(R.id.tv_finish);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.tv_btn:
//                handlerThread.start();
                myHandlerThread.start();
                mTvBtn.setEnabled(false);
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {

        switch (msg.what) {
            case DownLoadThread.TYPE_START:
                mTvStart.setText(mTvStart.getText().toString()+"   "+msg.obj);
                mTvBtn.setVisibility(View.VISIBLE);
                break;
            case DownLoadThread.TYPE_FINISHED:
                mTvFinish.setText(mTvFinish.getText().toString()+"   "+msg.obj);
                mTvBtn.setVisibility(View.GONE);
                break;
            default:
                break;
        }
        return true;
    }
}

///////DownLoadThread.java

public class DownLoadThread extends HandlerThread implements Handler.Callback {


    private final String KEY_URL = "url";
    public static final int TYPE_START = 1;
    public static final int TYPE_FINISHED = 2;
    private Handler uiHandler;
    private Handler workerHandler;


    private List urlLists;

    public DownLoadThread(String name) {
        super(name);
    }

    public DownLoadThread(String name, int priority) {
        super(name, priority);
    }


    @Override
    protected void onLooperPrepared() {
        super.onLooperPrepared();
        workerHandler = new Handler(getLooper(), this);

        if (uiHandler == null) {
            throw new IllegalArgumentException("not set uiHandler");
        }

        for (String url : urlLists) {
            Message message = workerHandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString(KEY_URL, url);
            message.setData(bundle);
            workerHandler.sendMessage(message);
        }

    }

    public void setUrlLists(String... urls) {
        urlLists = Arrays.asList(urls);
    }

    public Handler getUIHandler() {
        return uiHandler;
    }


    public DownLoadThread setUiHandler(final Handler handler) {
        uiHandler = handler;
        return this;
    }

    @Override
    public boolean handleMessage(Message msg) {

        if (msg == null || msg.getData() == null) {
            return false;
        }
        String path = (String) msg.getData().get(KEY_URL);


        Message startMsg = uiHandler.obtainMessage(TYPE_START, "开始下载 @" + System.currentTimeMillis() + "  url==" + path);
        uiHandler.sendMessage(startMsg);

        SystemClock.sleep(3000);


        Message finishMsg = uiHandler.obtainMessage(TYPE_FINISHED, "完成下载 @" + System.currentTimeMillis() + "  url==" + path);
        uiHandler.sendMessage(finishMsg);

        return true;
    }

    @Override
    public boolean quitSafely() {
        uiHandler = null;
        return super.quitSafely();
    }
}

///////MyHandlerThread.java

public class MyHandlerThread extends Thread implements Handler.Callback {

    private Handler handler;
    private final String KEY_URL = "url";
    public static final int TYPE_START = 1;
    public static final int TYPE_FINISHED = 2;

    private Handler workerHandler;

    private List urlLists;


    public MyHandlerThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        super.run();
        Looper.prepare();//@1111
        workerHandler = new Handler(this);
        for (String url : urlLists) {
            Message message = workerHandler.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString(KEY_URL, url);
            message.setData(bundle);
            workerHandler.sendMessage(message);
        }
        Looper.loop();//@2222
    }


    public void setUrlLists(String... urls) {
        urlLists = Arrays.asList(urls);
    }

    public Handler getUIHandler() {
        return handler;
    }


    public MyHandlerThread setUiHandler(final Handler handler) {
        this.handler = handler;
        return this;
    }

    @Override
    public boolean handleMessage(Message msg) {
        //处理相关消息;
        if (msg == null || msg.getData() == null) {
            return  false;
        }
        String path = (String) msg.getData().get(KEY_URL);


        Message startMsg = handler.obtainMessage(TYPE_START, "开始下载 @" + System.currentTimeMillis() + "  url==" + path);
        handler.sendMessage(startMsg);

        SystemClock.sleep(3000);


        Message finishMsg = handler.obtainMessage(TYPE_FINISHED, "完成下载 @" + System.currentTimeMillis() + "  url==" + path);
        handler.sendMessage(finishMsg);
        return true;
    }
}

很明显,再比对HandlerThread的源码可以发现,刨去安全性能问题,最大的区别就是我们自己使用Handler+Thread实现的时候需要注释中@1111和@2222两处的Looper.prepare()和Looper.loop()。O(∩_∩)O哈哈~

你可能感兴趣的:(重温HandlerThread)