12

我最近将我的应用程序更新到 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 是否有一些我不知道的变化?

4

2 回答 2

15

文档中

Android O 引入了通知通道来提供一个统一的系统来帮助用户管理通知。当您以 Android O 为目标时,您必须实现一个或多个通知通道来向您的用户显示通知。如果您不以 Android O 为目标,您的应用在 Android O 设备上运行时的行为与在 Android 7.0 上的行为相同。

(重点补充)

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

于 2017-07-04T21:02:31.133 回答
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;
}
于 2018-11-27T11:17:46.947 回答