使用Handler实现异步工作

本篇在https://blog.csdn.net/we1less/article/details/107892391上一篇的基础上进行对比

权限

 

http

android:usesCleartextTraffic="true"

布局




    

    

activity代码

package com.example.handlerdemo;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HandlerTest extends AppCompatActivity {

    ProgressBar progressBar;
    EditText editText;
    //1创建Handler成员变量对象 重写其handlerMessage()
    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            //判断标识
            if (msg.what == 1) {
                //5.在主线程处理消息
                String result = msg.obj.toString();
                editText.setText(result);
                //隐藏提示视图
                progressBar.setVisibility(View.INVISIBLE);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_test);
        progressBar = findViewById(R.id.pb_test_load);
        editText = findViewById(R.id.et_test_result);


    }

    //传统方式用线程做
    public void getSubmit1(View view) {
        //1.主线程显示提示视图
        progressBar.setVisibility(View.VISIBLE);
        //分线程联网请求
        new Thread() {
            public void run() {
                String path = "http://192.168.56.1:8080/Web_Server/index.jsp?name=godv&age=10";

                try {
                    final String result = requestToString(path);
                    //主线程显示
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            editText.setText(result);
                            //隐藏提示视图
                            progressBar.setVisibility(View.INVISIBLE);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //使用Handler
    public void getSubmit2(View view) {
        //1.主线程显示提示视图
        progressBar.setVisibility(View.VISIBLE);
        //分线程联网请求
        new Thread() {
            public void run() {
                String path = "http://192.168.56.1:8080/Web_Server/index.jsp?name=godv&age=10";

                try {
                    String result = requestToString(path);
                    //2 在分线程中  创建Message对象
                    Message message = Message.obtain();
                    //2指定标识
                    message.what = 1;
                    //3携带数据
                    message.obj = result;
                    //4使用Handler对象发送消息
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 请求服务器端, 得到返回的结果字符串
     *
     * @param path :http://192.168.56.1:8080/Web_Server/index.jsp
     * @return
     * @throws Exception
     */
    public String requestToString(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.connect();
        InputStream is = connection.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        baos.close();
        is.close();
        String result = baos.toString();
        connection.disconnect();
        return result;
    }
}

 

你可能感兴趣的:(安卓基础学习,android,移动开发)