• android--handler


    app在启动时会产生一个进程和一个线程,线程是主线程,又叫UI线程,更新UI元素必须要在UI线程中更新,否则会报错。

    在UI线程中有消息队列,子线程sendMessage到MQ中,looper类取出队列中的消息由UI线程中的Handler的handleMessage方法处理。

    public class HandlerTestActivity extends Activity {
        private TextView tv;
        private static final int UPDATE = 0;
        private Handler handler = new Handler() {
     
            @Override
            public void handleMessage(Message msg) {
                // TODO 接收消息并且去更新UI线程上的控件内容
                if (msg.what == UPDATE) {
                    // Bundle b = msg.getData();
                    // tv.setText(b.getString("num"));
                    tv.setText(String.valueOf(msg.obj));
                }
                super.handleMessage(msg);
            }
        };
     
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            tv = (TextView) findViewById(R.id.tv);
     
            new Thread() {
                @Override
                public void run() {
                    // TODO 子线程中通过handler发送消息给handler接收,由handler去更新TextView的值
                    try {
                        for (int i = 0; i < 100; i++) {
                            Thread.sleep(500);
                            Message msg = new Message();
                            msg.what = UPDATE;
                            // Bundle b = new Bundle();
                            // b.putString("num", "更新后的值:" + i);
                            // msg.setData(b);
                            msg.obj = "更新后的值:" + i;
                            handler.sendMessage(msg);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
     
    }
  • 相关阅读:
    CSS基本语法(慕课网学习笔记)
    Sublime Text3 显示左侧的目录树
    设置Sublime插件快捷键--实现CSS颜色选取
    HTML基本语法(慕课网学习笔记)
    cdoj1324卿学姐与公主
    模板-求组合数
    线段树--数据结构专题学习
    最短路径算法
    杭电1874畅通工程续 -最短路径
    杭电1027Ignatius and the Princess II模拟
  • 原文地址:https://www.cnblogs.com/jake-ge/p/4721509.html
Copyright © 2020-2023  润新知