Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // Tue, Wed...
calendar.set(Calendar.HOUR_OF_DAY, 1);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context,MyClass.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 7*24*60*60*1000, pi);
这将在星期一每周开一次,但是: 我想仅在工作日(没有星期六和星期日)设置待处理警报意图,如何只使用一个意图? 我不想使用5个不同的PendingIntents和5个不同的ID,因为那时我必须取消5
答案 0 :(得分:1)
无法将日历设置为多个日期,因此您无法按照自己喜欢的方式进行操作。
我建议你做的是每天重复报警并检查onReceive它是什么日子,如果它是星期六/星期日刚刚立即返回而且不做任何事情。
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 1);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyClass.class), 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, pi);
接收器
public class MyClass extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (today == sunday || today == saturday) {
return;
}
// do normal stuff.
}
}
答案 1 :(得分:1)
也许:
创建 setAlarm 方法:
public void setAlarm(long interval){
Calendar calendar = Calendar.getInstance();
//Alarm will go off at 1
calendar.set(Calendar.HOUR_OF_DAY, 1);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context,MyClass.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), interval, pi);
}
创建 cancelAlarm 方法(可选,如果您想在某处使用它):
public void cancelAlarm(Context context){
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context,MyClass.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(pi);
}
检查onReceive()
@Override
public void onReceive(Context context, Intent intent) {
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK); //Sunday = 1, Saterday = 7
switch(day){
case 6: //Friday
long interval = 3*24*60*60*1000 //skip saterday and sunday
setAlarm(interval);
case 2: //Monday
setAlarm(AlarmManager.INTERVAL_DAY); //Alarm will repeat everyday, until friday
break;
}
PS :不要忘记使用以下内容为第一次时间设置闹钟:setAlarm(AlarmManager.INTERVAL_DAY);
我认为这应该有用。