本文為大家介紹定時(shí)器刷新的詳細(xì)程序。
1、定時(shí)刷新 只刷新一次
首先要發(fā)送一個(gè)廣播 PendingTintent.getBroadcast()就類似于一個(gè)sendBroadcast
里面有四個(gè)參數(shù) 第一個(gè)就是context 第二個(gè)參數(shù)是個(gè)發(fā)送端的私人參數(shù),起區(qū)分作用 第三個(gè)intent 第四個(gè) flags參數(shù)可以指定PendingIntent的一些行為特點(diǎn),是用來針對Intent.fillIn() ,這里面沒有用到0即可。
PendingTintent 核心就是異步激發(fā) 有興趣的可以看
PnedingTingtent詳解
am.set()方法用來激發(fā),第一個(gè)參數(shù)是鬧鐘的類型 就不贅述了 第二個(gè)就是開始時(shí)間()
這個(gè)參數(shù)的類型要根據(jù)前一個(gè)鬧鐘的類型來的 , RTC_WAKEUP RTC POWER_OFF_WAKEUP使用的絕對時(shí)間,其他的類型就是相對時(shí)間 ,相對時(shí)間就是相對于開機(jī)時(shí)運(yùn)行的時(shí)間,絕對時(shí)間就是當(dāng)前的時(shí)間。
public static void sendUpdateBroadcast(Context context,long time){
AlarmManager am = context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(conext, UpdateReceiver.class);
i.putExtra(“time”, time);//time參數(shù)是刷新間隔
PendingIntent pendingIntent = PendingIntent.getBroadcast(contexxt, 0, i, 0);
//我這個(gè)是系統(tǒng)現(xiàn)在時(shí)間加上time時(shí)間進(jìn)行刷新
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, pendingIntent);
}
然后需要自定義一個(gè)接受器刷新的動作在這里面執(zhí)行
public static class UpdateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
long times=intent.getLongExtra(“time”,0);
Toast.makeText(context, “開始刷新”+intent.getLongExtra(“time”,0), Toast.LENGTH_SHORT).show();
}
}
2、定時(shí)刷新 根據(jù)間隔時(shí)間一直刷新
類似于鬧鐘
am.setRepeating ()第二個(gè)參數(shù)就是第一次刷新時(shí)間 (如果時(shí)間已經(jīng)過了,會馬上響應(yīng)一次),第三個(gè)就是間隔時(shí)間 。注意此廣播非覆蓋的 如若要改變刷新時(shí)間一定要先取消此廣播
public static void sendBroadcastRepeat(Context ctx,int hour,int minuter){
Intent intent =new Intent(ctx, RepeatReceiver.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, 00);
calendar.set(Calendar.MILLISECOND, 0);
AlarmManager am = getAlaramManager(ctx);
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), 1000 * 60 * 60 * 24, pendingIntent);
}
同樣也要寫一個(gè)接收器
public static class RepeatReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, “定時(shí)刷新”, Toast.LENGTH_SHORT).show();
}
}
-
定時(shí)器
+關(guān)注
關(guān)注
23文章
3256瀏覽量
115445 -
程序
+關(guān)注
關(guān)注
117文章
3798瀏覽量
81457
發(fā)布評論請先 登錄
相關(guān)推薦
評論