0

У меня есть приложение, которое показывает будильник в определенное время каждый день, я установил AlarmManager для этого. Теперь я хочу, чтобы мое постоянное уведомление прекратилось через час. Я знаю, что должен сделать еще один AlarmManager и отменить первый, но как я могу указать, что он должен быть отменен после «Часа»?Удалить постоянное уведомление с диспетчером аварийных сообщений

Calendar calender = Calendar.getInstance(); 
    calender.set(Calendar.HOUR_OF_DAY,01); 
    calender.set(Calendar.MINUTE, 00); 
    calender.set(Calendar.SECOND, 00); 
    Intent intent = new Intent(getApplicationContext(), AlertReceiver.class); 
    PendingIntent pendingintent = PendingIntent.getBroadcast(getApplicationContext(),100 
    ,intent,PendingIntent.FLAG_UPDATE_CURRENT); 
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(), 
      AlarmManager.INTERVAL_DAY, pendingintent); 

и это мой приемник:

NotificationManager notificationManager = (NotificationManager) context.getSystemService(context 
    .NOTIFICATION_SERVICE); 
    Intent repeating_intent = new Intent(context, SurveyActivity.class); 
    repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

    PendingIntent pendingIntent = PendingIntent .getActivity(context,100,repeating_intent, 
      PendingIntent.FLAG_UPDATE_CURRENT); 

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context) 
      .setContentIntent(pendingIntent) 
      .setSmallIcon(R.drawable.notiflogo) 
      .setContentTitle("Alarm") 
      .setContentText("This is Alarm") 
      .setTicker("Hello") 
      .setAutoCancel(true); 

    builder.setOngoing(true); 
    notificationManager.notify(100,builder.build()); 

ответ

0

Я думаю, вы знаете, что вы можете отменить уведомление по его идентификатору (вы установите его на 100 в Уре коде). Чтобы реализовать истечение срока действия, вам просто нужно установить еще один разовый (не повторяющийся) сигнал, который отменяет ваше уведомление. Вы установили, что сигнал тревоги сразу после показывать notifcation как это:

notificationManager.notify(100,builder.build()); 

AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
    Intent intent=new Intent(context,NotificationCancelReceiver.class); 
    intent.putExtra("notification_id", 100); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent, 0); 

    // Here's two way to fire a one-time (non-repeating) alarm in one hour 
    // One way: alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 60 * 60 * 1000, pendingIntent); 
    // Another way: 
    alarmManager.set(AlarmManager.ELAPSED_REALTIME, 
       SystemClock.elapsedRealtime() + 60 * 60 * 1000, pendingIntent); 
    // If you want to wake up the system with this alarm use ELAPSED_REALTIME_WAKEUP not ELAPSED_REALTIME 

А вот ваш NotificationCancelReceiver, что отменяет уведомление:

@Override 
public void onReceive(Context context, Intent intent) { 
     int id = intent.getIntExtra("notification_id", -1); 
     if (id != -1) { 
      NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
      notificationManager.cancel(id); 
     } 
} 

И убедитесь, что вы добавили приемник в AndroidManifest.xml

<receiver android:name=".NotificationCancelReceiver"> 
</receiver> 

Надеюсь, это поможет!

+0

Благодарим за отзыв, это именно то, что я хотел, но я не знаю, почему это не работает. Во-первых, я думаю, что в этой строке третий аргумент должен быть намеренным, я прав? 'PendingIntent pi = PendingIntent.getBroadcast (контекст, 0, pi, PendingIntent.FLAG_UPDATE_CURRENT); ', а затем я установил точно свою тревогу в течение одной минуты позже после моего конкретного времени для тестирования' alarmManager.set (AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 01 * 60 * 1000, pi); 'но уведомление по-прежнему там. Есть ли у вас другая идея? –

+0

Я отредактировал свой ответ. Пожалуйста, посмотрите. Не забудьте добавить приемник в AndroidManifest. И я перечислил два способа установить будильник, попробуйте каждый из них. Кроме того, я удалил действие настройки с намерением и проверил его внутри onRecieve. Да, критический аргумент PendingIntent.getBroadcast - это намерение - я ошибся в спешке. – Umarov

+0

Это полностью сработало, спасибо вам большое. –