Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

android - How to use alarmmanager 2 times every day?

I have used the following code to set alarmmanager for only one time every days, I'd like to have 2 different time to set, so 2 times every days.

My code:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 35);
calendar.set(Calendar.SECOND, 0);    AlarmManager am = (AlarmManager)     getApplicationContext().getSystemService  (Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(getApplicationContext(),     AlarmReceiver.class),      PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),     AlarmManager.INTERVAL_DAY, pi);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use an interval of AlarmManager.INTERVAL_DAY / 2 :

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 35);
 calendar.set(Calendar.SECOND, 0);    
AlarmManager am = (AlarmManager)getApplicationContext().getSystemService  (Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
 PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, intent,      PendingIntent.FLAG_UPDATE_CURRENT);
 am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),        AlarmManager.INTERVAL_DAY / 2, pi);

but if the time of the day in which you fire your alarm matters you can use two calendar objects :

Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.HOUR_OF_DAY, 12); //midday
cal1.set(Calendar.MINUTE, 00);
cal1.set(Calendar.SECOND, 00);

Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.HOUR_OF_DAY, 18);//8pm for example
cal2.set(Calendar.MINUTE, 00);
cal2.set(Calendar.SECOND, 00);

and set your alarm manager :

am.setRepeating(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(),cal2.getTimeInMillis(), pi);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...