android repeat alarm for every monday or every tuesday

假如想象 提交于 2019-12-29 01:26:48

问题


I am developing an alarm based application, in which i have to repeat the alarm for every weekday like (every monday, tuesday, wednesday) based on user input. I used this snippet

Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, alarmToSetInMilliSeconds, sender);

If user selects every monday means, i found the milliseconds more to next monday date and i set an alarm, and its working fine, how can i repeat it for other next monday, I want some idea to achieve it, any help are appreciated. Thanks.


回答1:


here is my code to set alarm to repeat every month in 4th

public void init(Context context) {

    Intent intent = new Intent(context, AlarmReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Get the AlarmManager service
    alarmManager = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);
}   
public void createAlarmControler(Context context) {

    init(context);
    Calendar cal = Calendar.getInstance();

    cal.set(Calendar.DAY_OF_MONTH, 4);
    cal.set(Calendar.HOUR_OF_DAY, 10);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    Date now = new Date(System.currentTimeMillis());
    if (cal.getTime().before(now)) {
        cal.add(Calendar.MONTH, 1);
    }
    long firstTime = cal.getTime().getTime();

    alarmManager.cancel(pendingIntent);
    Log.e("", "firstTime: " + firstTime);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, 1000 * 60
            * 60 * 24 * 30, pendingIntent);
}

public void cancelAlarmControler(Context context) {

    init(context);

    alarmManager.cancel(pendingIntent);
}


来源:https://stackoverflow.com/questions/13227035/android-repeat-alarm-for-every-monday-or-every-tuesday

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!