天天看点

使用Handler实现异步工作 -- 弱引用写法

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

权限

<uses-permission android:name="android.permission.INTERNET" />
           

http

android:usesCleartextTraffic="true"
           

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ProgressBar
        android:id="@+id/pb_test_load"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="invisible" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="getSubmit1"
        android:text="getSubmit1" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="getSubmit2"
        android:text="getSubmit2" />

    <EditText
        android:id="@+id/et_test_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
           

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;
    }
}
           

 弱引用写法

private SetBackGroundHandle mSetBackGroundHandle = new SetBackGroundHandle(this);

private static final int LOAD_BACK_GROUND_SUCCESS = 1;

mSetBackGroundHandle.sendEmptyMessage(LOAD_BACK_GROUND_SUCCESS);

private static class SetBackGroundHandle extends Handler {
        private final WeakReference<IrobotPlayerItemView> mWeakReference;

        private SetBackGroundHandle(IrobotPlayerItemView irobotPlayerItemView) {
            mWeakReference = new WeakReference<>(irobotPlayerItemView);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOAD_BACK_GROUND_SUCCESS:

                    //todo

                    break;
            }
        }
    }



@Override
protected void onDestroy() {
    super.onDestroy();
    mHandler.removeCallbacksAndMessages(null);
}