handle

handle 两个作用

  1. 子线程通知主线程
  2. 定时任务

 

package com.example.handleproject;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView textView=(TextView) findViewById(R.id.textView);
        //创建Handler,主线程
        final Handler handler=new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                TextView textView=(TextView) findViewById(R.id.textView);
                if(msg.what==1001){
                    textView.setText("immoc");
                }
                Log.d("TAG", String.valueOf(msg.arg1)+"==="+String.valueOf(msg.arg2));

            }
        };

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //有可能做大量耗时操作
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //1.子线程通知主线程更新
                        handler.sendEmptyMessage(1001);

                        Message message=Message.obtain();
                        message.what=1002;
                        message.arg1=1002;
                        message.arg2=1003;
                        message.obj=MainActivity.this;
                        /**
                         * 2.定时任务
                         *
                         * **/

                      //  handler.sendMessage(message);//立马执行
                        //3秒后触发
                     //   handler.sendMessageAtTime(message, SystemClock.uptimeMillis()+3000);
                        //延迟2秒后执行
                        handler.sendMessageDelayed(message,2000);
                     

                    }
                }).start();

            }
        });
    }


}

 

你可能感兴趣的:(android,handle)