2014-01-22 97 views
0

我想每天在特定時間發送廣播。我寫了一些代碼,但日曆返回錯誤的日期,廣播做了無限循環。我做錯了什麼?如何在AlarmManager中設置PendingIntent一段特定時間?

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

回答

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); 
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(),你得到CURR Date對象ENT時間(你也想希望通過使用TimeZone.getTimeZone(your_timezone)來傳遞你的時區作爲參數),所以你必須只設置小時和分鐘領域如下:

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

請檢查這個例子http://ideone.com/GN5ub1

+0

我知道,但我想它會自動設定當前日期,如果不工作,我需要檢查當天... – Grevius

相關問題