Android 在线程中修改 UI界面

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kidults/article/details/80799332

我们知道 Android 的 UI 是线程不安全的。也就是说,如果想要更新应用程序里的 UI 元素,则必须在主线程中进行,否则就会出现异常(崩溃)。

但是有些时候,我们必须在子线程里去执行一些耗时任务,然后根据任务的执行结果来更新相应的 UI 控件,这该如何是好呢?
对于这种情况,Android 提供了一套异步消息处理机制,完美地解决了在子线程中进行UI 操作的问题

直接上代码

     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");

    /*****************************************************
    修改界面
     ****************************************************/
    private Handler handle = new Handler() {
        public void handleMessage(Message msg) {
            switch(msg.what) {
                case UPDATE_TEXT:
                    //取出线程传过来的值String ss = (String) msg.obj;
                    Date date = new Date(System.currentTimeMillis()); //显示系统时间           
                    String str = String.format("%s",simpleDateFormat.format(date).toString());
                    m_View.setText(str);
                    break;
                default:
                    break;
            }
        }
    };


    class MyThread  implements Runnable {
        public void  run(){

            while(true){           

                        Message msg = new Message();
                        msg.what = UPDATE_TEXT;
                        //还可以通过message.obj = "";传值
                        handle.sendMessage(msg); //发送修改界面的消息


                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
            }

        }
    }
    MyThread thread = new MyThread();
    new Thread(thread ).start(); //开启线程

猜你喜欢

转载自blog.csdn.net/kidults/article/details/80799332