美文网首页
Android基础知识拾遗

Android基础知识拾遗

作者: 时光里捉迷藏 | 来源:发表于2019-05-09 13:58 被阅读0次

Android网络请求并将返回值加载到控件

1.使用runOnUiThread通知主线程

static void httpRequestWithUi(Activity activity, String url, View contentView) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            byte[] bytes = getRequestByUrl(url);

            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ((TextView) contentView).setText(new String(bytes));
                }
            });
        }
    }).start();
}

考虑一个问题Runnable的匿名对象在完成http请求获取到bytes之后怎么传值给外部?

2.使用Handler通知主线程

static void httpRequestWithHandler(String url, TextView contentView) {

    @SuppressLint("HandlerLeak") Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == 0x007) {
                contentView.setText((String) msg.obj);
            }
        }
    };

    new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            byte[] bytes = getRequestByUrl(url);

            Message message = handler.obtainMessage();
            message.what = 0x007;
            message.obj = new String(bytes);
            handler.sendMessage(message);
        }
    }).start();
}

查看Activity源码,其实runOnUiThread就是在当前Activity的Handler发送消息给UiThread

public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

所以第一种方法等价于

static void httpRequestWithUi(String url, View contentView) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            byte[] bytes = getRequestByUrl(url);

           new Handler().post(new Runnable() {
                @Override
                public void run() {
                    ((TextView) contentView).setText(new String(bytes));
                }
            });
        }
    }).start();
}

和第二种方法完全等价

相关文章

网友评论

      本文标题:Android基础知识拾遗

      本文链接:https://www.haomeiwen.com/subject/uadwoqtx.html