专业IM即时通讯软件开发,值得信赖!

Android原生通知推送兼容 8.0

未分类 云聊IM 704℃

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、创建通知渠道 Android8.0

NotificationManager notificationManager = (NotificationManager) 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(this);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
builder.setContentTitle("通知标题")//设置通知栏标题
        .setContentIntent(pendingIntent) //设置通知栏点击意图
        .setContentText("通知内容")
        .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) 不要遗漏了

版权声明:部分文章、图片等内容为用户发布或互联网整理而来,仅供学习参考。如有侵犯您的版权,请联系我们,将立刻删除。
喜欢 (0)
仿微信聊天软件开发
点击这里给我发消息