2012-11-27 102 views
0

我試圖設置一個鬧鐘,將意向發送到廣播接收器。然後接收者應該在logcat中打印一條表明它已經工作的行。但是我沒有收到任何跡象表明接收者正在接收任何東西。我已經檢查了所有我能想到的事情。由於我處於虧損狀態,有人能給我一些指導嗎?Android的鬧鐘管理器和BroadcastReceiver

報警方式

public void scheduleNextUpdate() 
     { 

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


     long currentTimeMillis = System.currentTimeMillis(); 
     long nextUpdateTimeMillis = currentTimeMillis * DateUtils.MINUTE_IN_MILLIS; 
     Time nextUpdateTime = new Time(); 
     nextUpdateTime.set(nextUpdateTimeMillis); 

     if (nextUpdateTime.hour < 8 || nextUpdateTime.hour >= 22) 
     { 
      nextUpdateTime.hour = 8; 
      nextUpdateTime.minute = 0; 
      nextUpdateTime.second = 0; 
      nextUpdateTimeMillis = nextUpdateTime.toMillis(false) + DateUtils.DAY_IN_MILLIS; 
     } 
     AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
     alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent); 
     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, nextUpdateTimeMillis,nextUpdateTimeMillis,pendingIntent); 

     boolean alarmUp = (PendingIntent.getBroadcast(this, 0, 
       new Intent(MainActivity.this,AlarmReceiver.class), 
       PendingIntent.FLAG_NO_CREATE) != null); 

     if (alarmUp) 
     { 
      Log.d("myTag", "Alarm is already active"); 
     } 
} 

ReceiverClass

public class AlarmReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     System.out.println("Alarm Received"); 
    intent = new Intent(context, MainActivity.class); 
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0); 
    System.out.println("Alarm Received"); 
} 

清單

<receiver android:name=".AlarmReceiver"></receiver> 
+0

您可以檢查您的鬧鐘是否正在註冊?在命令行/終端中鍵入** adb shell dumpsys alarm ** –

回答

4

這樣算算好象不對。我相信你正在嘗試設置鬧鐘不會熄滅了幾代:

long currentTimeMillis = System.currentTimeMillis(); 
long nextUpdateTimeMillis = currentTimeMillis * DateUtils.MINUTE_IN_MILLIS; 

也許你的意思的警報在一分鐘內熄滅:

long nextUpdateTimeMillis = currentTimeMillis + DateUtils.MINUTE_IN_MILLIS; 

反正第一次使用:

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
          System.currentTimeMillis() + 10000, 
          5000, 
          pendingIntent); 

要確認您的設置是正確的,如果這樣你就需要重新計算你的nextUpdateTimeMillis