2015-10-22 78 views
0

我嘗試每20秒啓動一個簡單的方法,我的想法是再次在此方法中啓動報警。要再次創建此類,在該方法中執行並正在啓動另一個警報...等等 該方法本身應該創建一個通知。Android報警管理器不會等待

public class CreateNotification extends BroadcastReceiver{ 
    public void onReceive(Context context, Intent intent) { 

     doStuff(); 

      NotificationCompat.Builder mNoteBuilder = 
        new NotificationCompat.Builder(context) 
          .setSmallIcon(R.drawable.icon) 
          .setContentTitle("...") 
          .setContentText(shownString) 

      //get an instance of the notificationManager service 
      NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
      //build the notification 
      mNotifyMgr.notify(mNotificationID, mNoteBuilder.build()); 

      createNewAlarm(context); 
    } 

     private void createNewAlarm(Context context){ 
      Intent alarmIntent = new Intent(context, CreateNotification.class); 
      PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0); 
      AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
      manager.set(AlarmManager.RTC_WAKEUP, 20000, pendingIntent); 
    } 
} 

這在我的主要活動開始:

Intent alarmIntent = new Intent(this, CreateNotification.class); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0); 
    AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE); 
    manager.set(AlarmManager.RTC_WAKEUP, 4000, pendingIntent); 

現在我的問題是,我沒有得到預期的結果,每20秒一個新的通知,但它創造的所有時間通知,與處理器一樣快。它們之間沒有任何中斷,警報管理員似乎也沒有安排任何事情,而是立即創建班級。

非常感謝您的幫助!

+0

我不使用重複報警的原因是,我需要改變每一個方法調用的意圖 – Jonas

回答

1
manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+20000, pendingIntent); 

您的解決方案:20000 = 1970年1月1日0時零零分20秒 所以你有你的毫秒添加到當前的時間。 (另一種解決方案來獲得當前的時間。)

Calendar calendar = Calendar.getInstance(); 
calendar.getTimeInMillis()+yourTimeInMillis; 
+0

謝謝,我一定是錯過了這一點文檔 – Jonas