5AlarmManager--全局定時器
(1)在指定時長后執(zhí)行某項操作
// 發(fā)送一個廣播,廣播接收后Toast提示定時操作完成
Intent intent =newIntent(Main.this, alarmreceiver.class);
intent.setAction("short");
PendingIntent sender=PendingIntent.getBroadcast(Main.this, 0, intent, 0);
// 設(shè)定一個五秒后的時間
Calendar calendar=Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 5); AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
Toast.makeText(Main.this, "五秒后alarm開啟", Toast.LENGTH_LONG).show();
(2)周期性的執(zhí)行某項操作
Intent intent =newIntent(Main.this, alarmreceiver.class);
intent.setAction("repeating");
PendingIntent sender=PendingIntent .getBroadcast(Main.this, 0, intent, 0);
//開始時間
long firstime=SystemClock.elapsedRealtime();
AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);
//5秒一個周期,不停的發(fā)送廣播 am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime, 5*1000, sender);
//注意:receiver記得在manifest.xml注冊
public static class alarmreceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if
(intent.getAction().equals("short")){
Toast.makeText(context, "short alarm",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context, "repeating alarm", Toast.LENGTH_LONG).show();
}
}
}
AlarmManager的取消:(其中需要注意的是取消的Intent必須與啟動Intent保持絕對一致才能支持取消AlarmManager)
Intent intent =new Intent(Main.this, alarmreceiver.class);
intent.setAction("repeating");
PendingIntent sender=PendingIntent.getBroadcast(Main.this, 0, intent, 0);
AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);
alarm.cancel(sender);
|