2015-10-22 177 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