Android 通知未显示 API 26

Android Notification Not Showing On API 26

我最近将我的应用程序更新到 API 26,通知不再有效,甚至没有更改代码。

val notification = NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("Title")
                .setContentText("Text")
                .build()
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(1, notification)

为什么它不起作用? API 是否有一些我不知道的变化?

来自the documentation

Android O introduces notification channels to provide a unified system to help users manage notifications. When you target Android O, you must implement one or more notification channels to display notifications to your users. If you don't target Android O, your apps behave the same as they do on Android 7.0 when running on Android O devices.

(强调)

您似乎没有将此 Notification 与频道相关联。

我在这里 post 一些快速解决方案

public void notification(String title, String message, Context context) { 
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    int notificationId = createID();
    String channelId = "channel-id";
    String channelName = "Channel Name";
    int importance = NotificationManager.IMPORTANCE_HIGH;

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel mChannel = new NotificationChannel(
                channelId, channelName, importance);
        notificationManager.createNotificationChannel(mChannel);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.app_logo)//R.mipmap.ic_launcher
            .setContentTitle(title)
            .setContentText(message)
            .setVibrate(new long[]{100, 250})
            .setLights(Color.YELLOW, 500, 5000)
            .setAutoCancel(true)
            .setColor(ContextCompat.getColor(context, R.color.colorPrimary));

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addNextIntent(new Intent(context, MainAcivity.class));
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);

    notificationManager.notify(notificationId, mBuilder.build());
}

public int createID() {
    Date now = new Date();
    int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss", Locale.FRENCH).format(now));
    return id;
}