Android-Handler机制方法调用

Handler通过runnable开启新线程,并传递信息

MainActivty.java

package com.example.handlerdemo;

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.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView textView;
    int count = 0;
    Handler countHandler = new Handler();

    Runnable mRunToast = new Runnable() {
        @Override
        public void run() {
            Toast.makeText(MainActivity.this, "hello toast", Toast.LENGTH_SHORT).show();
        }
    };

    Runnable mRunCount = new Runnable() {
        @Override
        public void run() {
            textView.setText("Count: "+String.valueOf(++count));
            countHandler.postDelayed(mRunCount,1000);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ((Button)findViewById(R.id.btnShowToast)).setOnClickListener(this);
        ((Button)findViewById(R.id.btnStart)).setOnClickListener(this);
        ((Button)findViewById(R.id.btnStop)).setOnClickListener(this);
        textView = findViewById(R.id.tvCount);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btnShowToast:
                countHandler.postAtTime(mRunToast,SystemClock.uptimeMillis()+1000);
                break;
            case R.id.btnStart:
                countHandler.postDelayed(mRunCount,1000);
                break;
            case R.id.btnStop:
                countHandler.removeCallbacks(mRunCount);
                break;

        }

    }

}

xml




    

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