2016-06-02 4 views
3

Извещение setAutoCancel (истина) не работает, если нажав на действияУведомление не увольняют (Android)

У меня есть уведомление с действием в нем. Когда я нажимаю на уведомление, он удаляется из списка. Однако, когда я нажимаю на действие, он успешно завершает действие (а именно делает вызов), но когда я возвращаюсь к списку уведомлений, он остается там. относительный код AlarmReceiver:

public class AlarmReceiver extends BroadcastReceiver { 
Meeting meeting; 

/** 
* Handle received notifications about meetings that are going to start 
*/ 
@Override 
public void onReceive(Context context, Intent intent) { 

    // Get extras from the notification intent 
    Bundle extras = intent.getExtras(); 
    this.meeting = extras.getParcelable("MeetingParcel"); 

    // build notification pending intent to go to the details page when click on the body of the notification 
    Intent notificationIntent = new Intent(context, MeetingDetails.class); 
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    notificationIntent.putExtra("MeetingParcel", meeting);  // send meeting that we received to the MeetingDetails class 
    notificationIntent.putExtra("notificationIntent", true); // flag to know where the details screen is opening from 

    PendingIntent pIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); 

    // build intents for the call now button 
    Intent phoneCall = Call._callIntent(meeting); 
    if (phoneCall != null) { 

     PendingIntent phoneCallIntent = PendingIntent.getActivity(context, 0, phoneCall, PendingIntent.FLAG_CANCEL_CURRENT); 

     int flags = Notification.FLAG_AUTO_CANCEL; 

     // build notification object 
     NotificationCompat.Builder builder = new NotificationCompat.Builder(context); 
     Notification notification = builder.setContentTitle("Call In") 
       .setContentText(intent.getStringExtra("contextText")) 
       .setTicker("Call In Notification") 
       .setColor(ContextCompat.getColor(context, R.color.colorBluePrimary)) 
       .setAutoCancel(true)     // will remove notification from the status bar once is clicked 
       .setDefaults(Notification.DEFAULT_ALL) // Default vibration, default sound, default LED: requires VIBRATE permission 
       .setSmallIcon(R.drawable.icon_notifications) 
       .setStyle(new NotificationCompat.BigTextStyle() 
         .bigText(meeting.description)) 
       .addAction(R.drawable.icon_device, "Call Now", phoneCallIntent) 
       .setCategory(Notification.CATEGORY_EVENT) // handle notification as a calendar event 
       .setPriority(Notification.PRIORITY_HIGH) // this will show the notification floating. Priority is high because it is a time sensitive notification 
       .setContentIntent(pIntent).build(); 

     notification.flags = flags; 

     // tell the notification manager to notify the user with our custom notification 
     NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
     notificationManager.notify(0, notification); 
    } 
    } 
} 

enter image description here

+0

Async - вы нашли решение своей проблемы. В настоящее время я столкнулся с той же проблемой? –

ответ

0

Вы создали две очереди намерения использовать в Боты и изменить флаг тоже.

PendingIntent pIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, 0); 

    PendingIntent phoneCallIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), phoneCall, PendingIntent.FLAG_UPDATE_CURRENT); 

// ИЗМЕНЕНИЕ ЭТОЙ

PendingIntent pIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); 

    PendingIntent phoneCallIntent = PendingIntent.getActivity(context, 0, phoneCall, PendingIntent.FLAG_CANCEL_CURRENT); 
+0

извините, что, не помогло –

+0

@ Async- см. Обновленный ответ –

+0

все еще не отменяет уведомление :( –

0

использовать этот флаг:

Notification.FLAG_AUTO_CANCEL внутри этого:

int flags = Notification.FLAG_AUTO_CANCEL; 
Notification notification = builder.build(); 
     notification.flags = flags; 

Documentation

+0

Я обновил код, как вы предлагали, но все же не повезло .. PLS см. Мой отредактированный код в вопросе (это правильно?) –

+0

@ Async-, да. Придется ли использовать очень-очень простое уведомление для тестирования? – Vyacheslav

+0

ok, оказывается, это уже известная проблема, я отправлю ссылку на другой вопрос stackoverflow об этом –

-1

Оказывается, это уже известная проблема, и ей нужен дополнительный код (ссылка на уведомление через id). Не знаю, почему API не предоставляет этого, поскольку это кажется очень логичным. Но в любом случае,

увидеть это answer in stackoverflow:

Когда вы позвонили оповещать о менеджере уведомлений вы дали ему идентификатор - это уникальный идентификатор можно использовать для доступа к нему позже (это от менеджера уведомлений :

notify(int id, Notification notification) 

Для отмены, вы могли бы назвать:

cancel(int id) 

с тем же идентификатором S. o, в основном, вам нужно отслеживать идентификатор или, возможно, помещать идентификатор в пакет, который вы добавляете к намерению внутри PendingIntent?