Android 8.0通知不显示

Android 8.0通知需要设置通知渠道才能正常显示,步骤如下:

*官方创建通知文档:https://developer.android.google.cn/training/notify-user/build-notification

1、定义通知id、通知渠道id、通知渠道名

private static final int PUSH_NOTIFICATION_ID = (0x001);
private static final String PUSH_CHANNEL_ID = "PUSH_NOTIFY_ID";
private static final String PUSH_CHANNEL_NAME = "PUSH_NOTIFY_NAME";

注:a.通知渠道id不能太长且在当前应用中是唯一的,太长会被截取。官方说明:

The id of the channel. Must be unique per package. The value may be truncated if it is too long.

        b.通知渠道名也不能太长推荐40个字符,太长同样会被截取。官方说明:

The recommended maximum length is 40 characters; the value may be truncated if it is too long.

2、创建通知渠道

NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(PUSH_CHANNEL_ID, PUSH_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
    if (notificationManager != null) {
        notificationManager.createNotificationChannel(channel);
    }
}

3、创建通知并显示

 
 
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
builder.setContentTitle("通知标题")//设置通知栏标题
        .setContentIntent(pendingIntent) //设置通知栏点击意图
        .setContentText("通知内容")
        .setNumber(++pushNum)
        .setTicker("通知内容") //通知首次出现在通知栏,带上升动画效果的
        .setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示,一般是系统获取到的时间
        .setSmallIcon(R.mipmap.ic_launcher)//设置通知小ICON
        .setChannelId(PUSH_CHANNEL_ID)
        .setDefaults(Notification.DEFAULT_ALL);

Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
if (notificationManager != null) {
    notificationManager.notify(PUSH_NOTIFICATION_ID, notification);
}
注:setChannelId(PUSH_CHANNEL_ID) 不要遗漏了,不然通知依然不显示。或者将
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
改为
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,PUSH_CHANNEL_ID);

猜你喜欢

转载自blog.csdn.net/u010231682/article/details/80732879