Android的Handler消息传递

为什么需要 Handler?

子线程不允许访问 UI,用Handler可以实现在子线程中修改主线程的UI,比如我在子线程中toast

 

 

 Handler+post实现

Handler handler=new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                /**
                 耗时操作
                 */
                Toast.makeText(MainActivity.this,"Starting",Toast.LENGTH_LONG).show();

                try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,"finished",Toast.LENGTH_LONG).show();
                    }
                });
            }
        }).start();

其中Start的toast要删除,因为在子线程中不能对ui操作

Handler+sendMessage实现

    void sendMessage(){
         Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {      //判断标志位
                    case 1:
                        /**
                         获取数据,更新UI
                         */
                        Toast.makeText(MainActivity.this,"receive:"+msg.obj,Toast.LENGTH_LONG).show();

                        msg.obj.toString();
                        break;
                }
            }
        };
         class WorkThread extends Thread {
            @Override
            public void run() {
                super.run();
                /**
                 耗时操作
                 */
                try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}

                //从全局池中返回一个message实例,避免多次创建message(如new Message)
                Message msg = Message.obtain();
                msg.obj = "data";
                msg.what=1;   //标志消息的标志
                handler.sendMessage(msg);
            }

        }
        new WorkThread().start();
    }

handler.post和handler.sendMessage本质上是没有区别的,都是发送一个消息到消息队列中,只不过post使用方式更简单

GitHub地址 下载前给star

posted @ 2022-11-02 13:07  Z_Chan  阅读(162)  评论(0编辑  收藏  举报