2016-04-23 3 views
1

У меня возникли трудности с закрытием моего уведомления, как только пользователь нажмет на него из панели уведомлений. Я знаю метод setAutoCancel, но он не работает. Вот мой код, тем не менее.Как закрыть уведомление, когда пользователь нажимает на него

MondayNotificationService.class

@Override 
public void onReceive(Context context, Intent intent) { 
    final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context); 
     builder.setSmallIcon(R.drawable.icon); 
     builder.setContentTitle(context.getString(R.string.app_name)); 

    if (intent.getAction().equalsIgnoreCase("FirstPeriod")) { 
     builder.setContentText("Microwave Engineering"); 
     builder.setContentIntent(PendingIntent.getActivity(context, 100, new Intent(context, Monday.class), 0)); 
     Notification notification = builder.build(); 
     builder.setAutoCancel(true); 
     int notificationID = 100; 
     notificationManager.notify(notificationID, notification); 

     Handler handler = new Handler(); 
     long delayInMilliseconds = 300000; 
     handler.postDelayed(new Runnable() { 
      public void run() { 
       notificationManager.cancel(100); 
      } 
     }, delayInMilliseconds); 

    } if (intent.getAction().equalsIgnoreCase("SecondPeriod")) { 
     builder.setContentText("Digital Signal Processing"); 
     builder.setContentIntent(PendingIntent.getActivity(context, 101, new Intent(context, Monday.class), 0)); 
     Notification notification = builder.build(); 
     int notificationID = 101; 
     builder.setAutoCancel(true); 
     notificationManager.notify(notificationID, notification); 

     Handler handler = new Handler(); 
     long delayInMilliseconds = 300000; 
     handler.postDelayed(new Runnable() { 
      public void run() { 
       notificationManager.cancel(101); 
      } 
     }, delayInMilliseconds); 
    } 

Monday.class

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_monday); 

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
    Calendar calendar = Calendar.getInstance(); 
    calendar.setTimeInMillis(System.currentTimeMillis()); 

    Intent firstIntent = new Intent(this, MondayNotificationService.class); 
    firstIntent.setAction("FirstPeriod"); 
    PendingIntent firstAlarmIntent = PendingIntent.getBroadcast(this, 100, firstIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
    calendar.set(2016, 3, 23, 20, 40, 0); 
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), firstAlarmIntent); 
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, firstAlarmIntent); 

    Intent secondIntent = new Intent(this, MondayNotificationService.class); 
    secondIntent.setAction("SecondPeriod"); 
    PendingIntent secondAlarmIntent = PendingIntent.getBroadcast(this, 101, secondIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
    calendar.set(2016, 3, 23, 20, 12, 0); 
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), secondAlarmIntent); 
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, secondAlarmIntent); 

Кроме того, когда уведомление истекает через 5 минут, и я открываю приложение и нажмите на кнопку "Понедельник" то все уведомления отображаются на панели уведомлений сразу (даже истекшие). Любая помощь в понимании того, что происходит неправильно, будет глубоко оценена.

+1

Вам нужно вызвать 'setAutoCancel()' перед вами 'сборки()' 'Notification'. –

ответ

3

Как указывает Майк М., вам необходимо настроить Builder перед вызовом build().

У вас есть:

Notification notification = builder.build(); 
    builder.setAutoCancel(true); 

Реверс эти строки:

builder.setAutoCancel(true); 
    Notification notification = builder.build(); 
+0

Указанный вами метод работает, но проблема в том, что всякий раз, когда я нажимаю на кнопку своего приложения, все уведомления выдаются одновременно. Любое исправление по этому поводу? –

+0

@SiddharthSaxena: Ну, вы устанавливаете два будильника, чтобы уйти два месяца назад (23 марта 2016 года). Попытайтесь выбрать время в будущем. :-) – CommonsWare

+0

Хорошо, я попробую :) –

0

notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL

Согласно документации

бит для поразрядно-Ored в поле флагов, которые должны быть установлены, если уведомление должно быть отменено при щелчке пользователем

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