Вопрос

I want to send a Broadcast at an specific time a day. I wrote some code, but the Calendar returns a wrong Date and the Broadcast does an infinite Loop. What have I done wrong?

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

The right code is this:

        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);

Другие советы

You are setting calendar in a wrong way. Calendar.YEAR, Calendar.MONTH, etc. are the field numbers, not current Date values. The proper way is like that:

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

So Calendar.YEAR is always equals to 1, Calendar.MONTH is always equals to 2. You calendar set up should be like so:

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

You can take a look here http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

EDIT

When you call getInstance(), you get Date object with current time (you may want also want to pass your timezone as parameter by using TimeZone.getTimeZone(your_timezone)), so you have to set only the hour and minute fields as follow:

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

Please check this example http://ideone.com/GN5ub1

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top