2013-07-29 3 views
1

Я хочу отобразить случайное уведомление в течение дня, поэтому я установил будильник, который принимает время, которое будет запускаться в качестве значения через мои общие настройки, значение по умолчанию - 10. Код следующий:Время обновления в AlarmManager

Calendar calendar; 

    SharedPreferences prefs = PreferenceManager 
      .getDefaultSharedPreferences(getBaseContext()); 
    int nextAlarm = prefs.getInt("nextAlarm", 10); 

    Intent i = new Intent(this, NotificationBarAlarm.class); 
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

    PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 
      PendingIntent.FLAG_UPDATE_CURRENT); 


    calendar = Calendar.getInstance(); 
    calendar.set(Calendar.HOUR_OF_DAY, nextAlarm); 
    calendar.set(Calendar.MINUTE, 00); 
    calendar.set(Calendar.SECOND, 00); 

    long alarmmills = calendar.getTimeInMillis(); 

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
    am.set(AlarmManager.RTC_WAKEUP, alarmmills, pi); 

Тревога отправляет ожидающее намерения активировать мой процесс уведомления. Всякий раз, когда вызывается уведомление, я вычисляю текущее время миллисекунды плюс случайное количество миллисекунд, я конвертирую их в часы и сохраняю время в своем общем предпочтении, чтобы использовать его для следующего сигнала тревоги. Наконец я отправить Намерение моей тревоги службы так, чтобы обновить it.The код имеет следующий вид:

NotificationManager notifyManager; 

@Override 
public void onReceive(Context context, Intent intent) { 


    Time time = new Time(); 
    long currenttimeMilliseconds = System.currentTimeMillis(); 
    time.set(currenttimeMilliseconds); 
    int t = time.hour; 

    //Random time 

    Random rand=new Random(); 
    int min = 1, max = 2; 
    int randomNum = rand.nextInt(max - min + 1) + min; 
    long randomMilli=randomNum *60*60*1000; 

     long updatedTime= currenttimeMilliseconds + 10800000 +randomMilli; 

     Time nextalarmmill = new Time(); 
     nextalarmmill.set(updatedTime); 
     int nextalarm = nextalarmmill.hour; 

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); 
    SharedPreferences.Editor editor = prefs.edit(); 
    editor.putInt("nextAlarm", nextalarm); 
    editor.commit(); 


    if (t >= 10 && t <= 22) {   

     notifyManager = (NotificationManager) context 
       .getSystemService(Context.NOTIFICATION_SERVICE); 
     Intent notificationIntent = new Intent(context, 
       AlarmReceiverActivity.class); 
     PendingIntent contentIntent = PendingIntent.getActivity(context, 0, 
       notificationIntent, 0); 
     Notification notif = new Notification(R.drawable.ic_launcher, 
       "A new notification just popped in!", 
       System.currentTimeMillis()); 
     Uri alarmSound = RingtoneManager 
       .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     notif.sound = alarmSound; 
     notif.setLatestEventInfo(context, "Notification", 
       "A new notification", contentIntent); 
     notifyManager.notify(1, notif); 

    } 

    Intent serviceIntent = new Intent(context, AlarmService.class); 
    context.startService(serviceIntent); 


} 

Он правильно работает до тех пор пока изменения в день. Например, 27/07, когда в 21:00 я вызываю уведомление, что следующий сигнал тревоги активируется (случайным образом через 4 или 5 часов) позволяет говорить в 01:00. Тревога не понимает, что 01:00 не относится к сегодняшнему дню (27/07), а к следующему (28/7). В результате он немедленно запускает мой приемник уведомлений, который, в свою очередь, снова активирует мою службу сигнализации, создающую цикл.

Как я могу установить будильник, чтобы понять, когда изменился день?

ответ

0

Попробуйте добавить, что:

if (nextAlarm < calendar.HOUR_OF_DAY) 
    calendar.add(Calendar.DATE, 1); 

после

calendar = Calendar.getInstance(); 
+0

Я просто попытался это, но, к сожалению, до сих пор сталкиваются с той же проблемой – tassos81

Смежные вопросы