1. 程式人生 > >Android 8.0通知不顯示

Android 8.0通知不顯示

Android 8.0通知需要設定通知渠道才能正常顯示,步驟如下:

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