ThreadHander多线程

ThreadHander多线程_第1张图片
效果图

MainActivity.java


ThreadHander多线程_第2张图片
package com.example.threaddemo;

import android.nfc.Tag;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.lang.ref.WeakReference;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    Handler handler;
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
//        主线程
        handler = new MyHandler(this);
        //查看当前线程,
        Log.d("TAG", "主线程 name:" +  Thread.currentThread().getName());

    }
    public void download(View v){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("TAG", "子线程 name:" +  Thread.currentThread().getName());
//                模拟下载
                for(int i=0;i<=100;i++){
                    try {
                        Thread.sleep(100);
                        handler.sendEmptyMessage(i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
//        子线程开始
        thread.start();
    }
    static class MyHandler extends Handler{
//      通过WeakReference实现对Activity的弱引用
        private WeakReference activityWeakReference;
//        构造函数
        MyHandler(MainActivity activity){
//            弱引用的封装
            this.activityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//            得到得消息
            String str = "Percent:"+msg.what;
//            弱引用的get返回一个activity
            activityWeakReference.get().textView.setText(str);
        }
    }
}



你可能感兴趣的:(ThreadHander多线程)