GCM notification setAutoCancel (true) not working in Android 5.1.1

I'm showing a notification with this code, but setAutoCancel (true) doesn't work because when I click on the notification to open the app, the notification is still on the notification bar and I have to delete it manually with a finger swipe to delete notifications or using Clear All buttons from the notification bar.

It works fine in android 4.4.2 device, but it doesn't work in my nexus 7 with 5.1.1

What's wrong?

private void generateNotification(Context context, String message) {

    Intent intent = new Intent(GCMListenerService.this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);

    Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    String appName = context.getResources().getString(R.string.app_name);       

    int width;
    int height;
    if (Util.checkAndroidVersionUpperOrEqualThan(11)){      
        width = getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_width); 
        height = getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
    }else{
        width = 64;
        height = 64;
    }

    image = Bitmap.createScaledBitmap(image, width, height, false);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
    .setSmallIcon(R.drawable.ic_launcher)
    .setLargeIcon(image)
    .setContentTitle(appName)
    .setContentText(message)
    .setSound(defaultSoundUri)
    .setPriority(NotificationCompat.PRIORITY_HIGH)
    .setContentIntent(pendingIntent)
    .setAutoCancel(true)
    .setStyle(new NotificationCompat.BigTextStyle().bigText(message));

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0,notificationBuilder.build());

}

      

+3


source to share


1 answer


You must set the notification flag with .setOngoing (true)



   val builder = NotificationCompat.Builder(context, channelId)
   builder.setOngoing(true)
   notification = builder.build()
   notification.flags = Notification.FLAG_ONGOING_EVENT

      

0


source







All Articles