Android定時執行任務可以通過以下幾種方式實現:
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
// 定時任務邏輯
handler.postDelayed(this, 1000); // 1秒后再次執行
}
};
handler.postDelayed(runnable, 1000); // 1秒后執行
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// 設置定時任務,每隔1分鐘執行一次
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60 * 1000, pendingIntent);
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
Runnable runnable = new Runnable() {
@Override
public void run() {
// 定時任務邏輯
}
};
scheduledExecutorService.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS); // 每隔1秒執行一次
以上是三種常用的實現方式,開發者可以根據具體需求選擇合適的方式來實現定時執行任務。