安卓开发之常见Handler API和 定时器的使用

时间:2022-03-29 23:20:16
package com.lidaochen.test;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends AppCompatActivity {
    private Timer timer;
    private TimerTask timerTask;
    private TextView tv;
    public static int num;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 获取TextView控件
        tv = (TextView)findViewById(R.id.tv);
        num = 0;
        // 5秒钟后执run方法
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                tv.setText("我是你爷爷!");
                Toast.makeText(getApplicationContext(), "我是你爸爸!", Toast.LENGTH_LONG).show();
            }
        }, 5000);
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                num++;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText("呵呵呵!" + num);
                    }
                });
            }
        };
        // 3 秒后每隔一秒钟执行一次run方法
        timer.schedule(timerTask, 3000, 1000);
    }

    @Override
    // 当Activity销毁的时候会执行这个方法
    protected void onDestroy() {
        timer.cancel();
        timerTask.cancel();
        super.onDestroy();
    }
}