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个不同的PendingIntent与5个不同的ID一起使用,因为那样我就必须取消5个

最佳答案

也许:

创建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);第一次将闹钟设置在某个地方

我认为这应该有效。

关于android - 闹钟仅在工作日重复,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35698160/

10-09 04:24