如何在AlarmManager中设置PendingIntent特定时间?

时间:2014-01-22 20:38:32

标签: android android-intent alarmmanager android-calendar

我想在一天的特定时间发送广播。我写了一些代码,但日历返回错误的日期,广播做了无限循环。我做错了什么?

Boolean static1Active = prefs.getBoolean("static_switch1", true);
    Log.i("HHG", "Static1? " + (INTENT_TYP.equals("static1") && static1Active));
    if(INTENT_TYP.equals("static1") && static1Active){
        String check_time1 = prefs.getString("check_time1", "6:0");
        String[] pieces=check_time1.split(":");
        Integer hour = Integer.parseInt(pieces[0]);
        Integer minute = Integer.parseInt(pieces[1]);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, Calendar.MONTH, Calendar.DATE, hour, minute);
        Log.i("HHG","Calendar: " +calendar.getTime());

        Intent static1 = new Intent(context, VertretungCheck.class);
        static1.putExtra("typ", "static1");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, static1, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    }

2 个答案:

答案 0 :(得分:2)

您正在以错误的方式设置日历。 Calendar.YEAR,Calendar.MONTH等是字段编号,而不是当前日期值。正确的方法就是这样:

calendar.set(Calendar.YEAR, your_year);
calendar.set(Calendar.MONTH, your_month);
...

所以Calendar.YEAR总是等于1,Calendar.MONTH总是等于2.你的日历设置应该是这样的:

calendar.set(desired_year, desired_month (0 to 11), desired_date, hour, minute);

您可以在此处查看http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

修改

当您调用getInstance()时,您将获得具有当前时间的Date对象(您可能还希望通过使用TimeZone.getTimeZone(your_timezone)将您的时区作为参数传递),因此您只需设置小时和分钟字段如下:

calendar.set(Calendar.HOUR_OF_DAY, your_hour);
calendar.set(Calendar.MINUTE, your_minute);

请查看此示例http://ideone.com/GN5ub1

答案 1 :(得分:0)

正确的代码是:

        Calendar calendar = Calendar.getInstance();
        calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),   calendar.get(Calendar.DAY_OF_MONTH), hour, minute);