Android使用Joda Time设置重复闹钟

时间:2014-04-13 05:25:20

标签: java android alarmmanager jodatime repeatingalarm

我正在尝试使用JodaTime在每个月的星期一和星期三设置Android闹钟。我一直在互联网上搜索几个小时,但是当我使用JodaTime时,我无法找到alarmMgr.setRepeating()中的间隔。这是我的问题代码:

import java.util.Calendar;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;

public class SampleAlarmReceiver extends WakefulBroadcastReceiver {
 public static int firstOrSecond; //used for 1st, 2nd....
    //Joda time calculation for 1st, 2nd... sunday, monday... of month
    public static LocalDate nthWeekdayOfMonth(int dayOfWeek, int month, int year, int n) {
        LocalDate start = new LocalDate(year, month, firstOrSecond);
        LocalDate date = start.withDayOfWeek(dayOfWeek);
        return (date.isBefore(start)) ? date.plusWeeks(n) : date.plusWeeks(n - 1);
    }

// BEGIN_INCLUDE(set_alarm)
    public void setAlarm(Context context) {
        alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, SampleAlarmReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(context, 700, intent, 0);

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, 6);
        calendar.set(Calendar.HOUR_OF_DAY, MainActivity.hour);
        calendar.set(Calendar.MINUTE, MainActivity.minute);

        //Using Joda Time
        DateTime jodaCal; 
        jodaCal = new DateTime(calendar);
        DateTime triggerMillis = new DateTime();
        triggerMillis = jodaCal.isBefore(triggerMillis) ? jodaCal.plusWeeks(firstOrSecond) : jodaCal.plusWeeks(firstOrSecond - 1);
        long jodaMillis = triggerMillis.getMillis();

        //Set repeating alarm
        alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
                jodaMillis, /*What to put here for interval if I want to repeat alarm 2nd Wednesday of Every Month*/, alarmIntent);

        // Enable {@code SampleBootReceiver} to automatically restart the alarm when the
        // device is rebooted.
        ComponentName receiver = new ComponentName(context, SampleBootReceiver.class);
        PackageManager pm = context.getPackageManager();

        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

    }
}

0 个答案:

没有答案