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

android 安卓子线程和主线程交互实现方法

程序员文章站 2022-12-11 08:50:06
android 安卓子线程和主线程交互实现方法。 1.安卓为什么要执行子线程,什么情况下用子线程? 答:将消耗时间的任务放到子线程中执行,保证主线程ui的流畅性。 2.具体实现 当需要请求网络数据的...

android 安卓子线程和主线程交互实现方法。

1.安卓为什么要执行子线程,什么情况下用子线程?

答:将消耗时间的任务放到子线程中执行,保证主线程ui的流畅性。

2.具体实现

当需要请求网络数据的时候,会把请求过程放在子线程里,主线程调用的时候直接是checkbag(参数)。

比如我需要类似于web的ajax验证

public void checkbag(final string bagcode){
        //取出后端的数据
        thread thread = new thread("thread1") {
            httpurlconnection connection = null;
            bufferedreader reader = null;
            public void run() {
                string url = tools.getpropertiesurl(captureactivity.this,"url.prop","urlcheck");
                //show(url);
                try {
                    string responsesend = httpcheck.checkbag(bagcode,url);
                    //消息机制
                    bundle bundle = new bundle();
                    bundle.putstring("result",responsesend);
                    bundle.putstring("bagcode",bagcode);
                    message msg = new message();
                    msg.setdata(bundle);
                    myhandler.sendmessage(msg);
                    msg.what = 0;
                } catch (exception e) {
                    e.printstacktrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (ioexception e) {
                            e.printstacktrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            };
        };
        thread.start();
    }

用message或者buddle进行和主线程通信,

主线程有一个handler,handler包含线程队列和消息队列,实现异步消息处理机制。

主要作用有:1.运行在某个线程上,共享线程的消息队列。2.接收消息、调度消息、派发消息和处理消息。3.实现消息的异步处理。

简单理解为:一个连接主线程和子线程的工具。

上面的代码中有

myhandler.sendmessage(msg);
msg.what = 0;

这是讲请求返回的数据发送到主线程,并添加一个标识 what,这个what很重要,用来区分哪个线程发送的数据。子线程发送数据后需要主线程来接受,在哪接受呢?就是handler,hander的代码:

private static class myhandler extends handler {
    private final weakreference mactivity;

    public myhandler(captureactivity activity) {
        mactivity = new weakreference(activity);
    }

    @override
    public void handlemessage(message msg) {
        super.handlemessage(msg);
        bundle bundle = new bundle();
        bundle = msg.getdata();
        if (mactivity.get() == null) {
            return;
        }
        mactivity.get().updateuithread(msg);
    }
}
updateuithread(msg);

handler是一个中转的过程,需要将msg传到更新主线程的方法中,上面updateuithread(msg)就是起这么个作用。

updateuithread代码是:

private void updateuithread(message msg){
        switch (msg.what){
            case 0:
                //what标识为0的线程执行操作,填充数据,跳转等
                break;
            case 1:
????????????????//what标识为1的线程执行操作
                break;
            default:
                //默认的情况
                break;
        }
    }

所以就实现了线程和主线程直接的通信