欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android使用handler ui线程和子线程通讯更新ui示例

程序员文章站 2022-06-29 09:31:53
复制代码 代码如下:package com.act262.sockettx; import android.app.activity;import android.os....

复制代码 代码如下:

package com.act262.sockettx;

import android.app.activity;
import android.os.bundle;
import android.os.handler;
import android.os.message;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.button;
import android.widget.edittext;
import android.widget.textview;

/**
 * 可以在其他线程中获取view类的数据,但是不能修改或者设置view类的数据
 *
 */
public class main extends activity {

    textview result = null;
    edittext get = null;
    button update = null;
    handler handler;

    public void oncreate(bundle bundle) {
        super.oncreate(bundle);
        setcontentview(r.layout.main);
        result = (textview) findviewbyid(r.id.result);
        update = (button) findviewbyid(r.id.update);
        get = (edittext) findviewbyid(r.id.get);

        handler = new handler() {
            public void handlemessage(message msg) {
                if (msg.what == 1) {
                    result.settext("after update ui "
                            + msg.getdata().getstring("data")
                            + "  \nman thread : "
                            + thread.currentthread().getname());
                }
            }
        };

        result.settext("before update ui  main thread : "
                + thread.currentthread().tostring());

        update.setonclicklistener(new onclicklistener() {

            @override
            public void onclick(view v) {
                // todo auto-generated method stub
                new mythread("my thread").start();
            }
        });

    }

    class mythread extends thread {
        public mythread(string name) {
            super(name);
        }

        @override
        public void run() {
            // 发送不带数据的消息
            // handler.sendemptymessage(1);

            // 发送附带数据的消息
            message msg = new message();
            bundle data = new bundle();
            data.putstring("data", get.gettext().tostring() + " my thread:  "
                    + thread.currentthread().getname());
            msg.setdata(data);
            msg.what = 1;
            handler.sendmessage(msg);
        }
    }
}