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);

更多相关文章

  1. Android(安卓)O使用通知遇到的坑
  2. Android屏蔽通知栏的下拉
  3. Android(安卓)利用BroadcastReceiver实时检测网络状态变化
  4. android 使用现成做get请求
  5. Android适用于IM通知音频的Vibrator
  6. Android之不能静态注册的系统广播(5个)
  7. android CursorAdapter的监听事件
  8. Android(安卓)Studio 教程
  9. Android开发中ConnectivityManager应用

随机推荐

  1. 修改android系统和watchdog的延时
  2. 【转】Android(安卓)Pull解析xml
  3. 转:Game Engines for Android (Android游
  4. android用户界面-组件Widget-画廊视图Gal
  5. Android中讯飞语音云开发环境搭建
  6. android 下写文件性能测试
  7. APP开发实战94-Vector静态图的使用
  8. 第17天android:《android从零开始》视频(1-
  9. android 拨打紧急号码,通话时开启免提功能
  10. android 快速查询通讯录