在Android 5.1.1上,GCM通知的setAutoCancel(true)无法正常工作。

3
我正在使用以下代码显示通知,但setAutoCancel(true)无效,因为当我点击通知以打开应用程序时,通知仍然在通知栏上,并且我必须使用手势删除通知或使用通知栏中的清除所有按钮手动删除它。
在Android 4.4.2设备中,它可以正常工作,但在我的Nexus 7上,它不能正常工作。出了什么问题?
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());

}

使用.setCategory(Notification.CATEGORY_MESSAGE)与所有其他选项一起使用,包括setAutocancel和其他选项。 - Pankaj
Notification.CATEGORY_MESSAGE 适用于 API Level 21... 无法使用较低的编译 API 级别解决此问题吗? - NullPointerException
我尝试使用常量的值,但不起作用... .setCategory("msg") - NullPointerException
你之前询问的是5.1.1,它是API 22,显然比较高。请不要使用"msg",而是使用Notification.CATEGORY_MESSAGE - Pankaj
我尝试使用.setCategory(NotificationCompat.CATEGORY_MESSAGE),但没有起作用.... :/ - NullPointerException
1个回答

0

你必须使用.setOngoing(true)来设置通知标志。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接