说明:
两种方法实现android定时器,定时执行任务
第一种方式:
step1:
package com.example.iosdialogdemo;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Timer;
public class TimerActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_same);
Timer timer = new Timer();
timer.schedule(new MyTimerTask(), 0, 1000);
}
}
step2:
package com.example.iosdialogdemo;
import java.util.TimerTask;
public class MyTimerTask extends TimerTask {
@Override
public void run() {
System.out.println("this timer click");
}
}
第二种方式
step1:
package com.example.iosdialogdemo;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
public class TimerActivity extends AppCompatActivity {
private final int Time = 1000; //时间间隔, 单位 ms
private int N = 0; //用来观测重复执行
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_same);
handler.postDelayed(new Runnable() {
@Override
public void run() {
handler.postDelayed(this, Time);
//每隔一段时间要重复执行的代码
N = N + 1;
System.out.println("第" + N + "次执行");
}
}, Time); //启动计时器
}
}
第三种方式:
package com.example.iosdialogdemo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Timer;
public class TimerActivity extends AppCompatActivity {
private static Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
System.out.println("this timer click");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.sendEmptyMessage(0);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_same);
mHandler.sendEmptyMessage(0);
}
}
end