Android通知未在API 26上显示

Aar*_*ron 10 notifications android kotlin android-8.0-oreo

我最近将我的应用更新为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)
Run Code Online (Sandbox Code Playgroud)

为什么不工作?是否有一些我不知道的API更改?

Com*_*are 15

文档:

Android O引入了通知渠道,以提供统一的系统来帮助用户管理通知.当您定位Android O时,您必须实施一个或多个通知渠道以向您的用户显示通知.如果您没有定位Android O,则在Android O设备上运行时,您的应用与Android 7.0上的应用行为相同.

(重点补充)

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

  • 这样就解决了。Notification.Builder上的文档尚未更新以反映这一点。谢谢! (2认同)

小智 10

在这里,我发布了一些快速解决方案

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;
}
Run Code Online (Sandbox Code Playgroud)