Android uses alarm to enable a simple timer refresh and periodic refresh of timers
Alarmmanger's acquisition
Alarmmanger am= Context.getsystemservice (context.alarm_service)
The general implementation of the timer is broadcast through the form.
1. Timed Refresh is refreshed only once
The first to send a broadcast pendingtintent.getbroadcast () is similar to a sendbroadcast
There are four parameters in the first one is the context the second parameter is a private parameter of the sender, the third intent fourth flags parameter can be specified pendingintent some behavioral characteristics, is used for Intent.fillin (), It doesn't take 0.
The Pendingtintent core is the asynchronous excitation of interest can be seen
Pnedingtingtent detailed
The Am.set () method is used to excite, the first argument is the type of the alarm clock, and the second one is
publicstaticvoidsendUpdateBroadcast(Context context,long time){ AlarmManager am = context.getSystemService(Context.ALARM_SERVICE); new Intent(conext, UpdateReceiver.class); i.putExtra("time", time);//time参数是刷新间隔 00); //我这个是系统现在时间加上time时间进行刷新 am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, pendingIntent); }
Then you need to customize the action of a receiver refresh in this face
publicstaticclass UpdateReceiver extends BroadcastReceiver { publicvoidonReceive(Context context, Intent intent) { long times=intent.getLongExtra("time",0); "开始刷新"+intent.getLongExtra("time",0), Toast.LENGTH_SHORT).show(); } }
2 timed refresh always refreshes based on interval time
Similar to an alarm clock
Am.setrepeating () The second parameter is the first refresh time (if the time has elapsed, will respond immediately), and the third is the interval time
public static void Sendbroadcastrepeat (Context ctx,int hour,int minuter) {Intent Intent =new Intent (CTX, repeatrece Iver. Class);Intent. PutExtra("Hour", hour);Intent. PutExtra("Minuter", Minuter);Pendingintent pendingintent = pendingintent. Getbroadcast(CTX,0, Intent,0);Calendar Calendar = Calendar. getinstance();Calendar. Set(Calendar. HOUR_of_day, hour);Calendar. Set(Calendar. MINUTE, Minuter);Calendar. Set(Calendar. SECOND,xx);Calendar. Set(Calendar. Millisecond,0);Alarmmanager am = Getalarammanager (CTX);Am. setrepeating(Alarmmanager. RTC_wakeup,calendar. Gettimeinmillis(), +* -* -* -, pendingintent);}
Also write a receiver
publicstaticclass RepeatReceiver extends BroadcastReceiver { publicvoidonReceive(Context context, Intent intent) { "定时刷新", Toast.LENGTH_SHORT).show(); } }
3 Don't forget to register for the broadcast
Timer for simple timing refresh and periodic refresh