在 android 中有一些用于刷新处理的选项,例如Timer、TimerTask、ScheduledExecutorService、AlarmManager 和 Handler。这是执行此操作的最佳方法。
有没有人检查上述方法的资源利用率?我在这里列出了上述方法的实现。
使用 Handler 重复执行任务
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
new MyScheduledTask.execute(param);
}
}, TimeInterval);
使用 Timer 重复执行任务
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
new MyScheduledTask.execute(param);
}
}}, 10000, 10000);
使用 ScheduledExecutorService 重复执行任务
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate
(new Runnable() {
public void run() {
new MyScheduledTask.execute(param);
}
}, 0, 10, TimeInterval);
使用 Timer 和 TimerTask 重复执行任务
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(),1, TimeInterval);
class UpdateTimeTask extends TimerTask {
public void run()
{
new MyScheduledTask.execute(param);
}
}
AlarmManager 用于执行计划任务
public void setupTask(){
// check task is scheduled or not
boolean alarmUp = (PendingIntent.getBroadcast(this, 0,
new Intent("YourPackageHere.AlarmReceiver"),
PendingIntent.FLAG_NO_CREATE) != null);
if ( !alarmUp) {
Intent intent = new Intent("YourPackageHere.AlarmReceiver");
intent.putExtra("activate", true);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 1);
calendar.set(Calendar.SECOND, 0);
AlarmManager alarmManager =
(AlarmManager)
this.getSystemService(this.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
pendingIntent);
calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 7);
calendar.set(Calendar.MINUTE, 0);
alarmManager = (AlarmManager)
this.getSystemService(this.ALARM_SERVICE);
PendingIntent pendingIntent2 =
PendingIntent.getBroadcast(this, 1,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent2);
}
}
报警管理器类
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra("activate")) {
new MyScheduledTask.execute(param);
}
}
}
显现
<receiver android:name="YourPackageHere.AlarmReceiver"></receiver>