0

我正在android中做推送通知。以下代码块在 API 级别 22 中不起作用。

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new 
        NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }

如何在 API 级别 22 中执行此操作

4

2 回答 2

0

您可以尝试以下源代码

public void showNotification()
{
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,"channelID")
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setContentTitle("Notification")
            .setContentText("Hello! This is a notification.")
            .setAutoCancel(true);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    int notificationId = 1;
    createChannel(notificationManager);
    notificationManager.notify(notificationId, notificationBuilder.build());
}

public void createChannel(NotificationManager notificationManager){
    if (Build.VERSION.SDK_INT < 26) {
        return;
    }
    NotificationChannel channel = new NotificationChannel("channelID","name", NotificationManager.IMPORTANCE_DEFAULT);
    channel.setDescription("Hello! This is a notification.");
    notificationManager.createNotificationChannel(channel);
}

此代码适用于每个 android 版本。这是git 仓库

于 2021-01-11T08:18:34.113 回答
0

API 22 中没有 NotificationChannel。该功能仅在 API >=26 中可用。

于 2018-09-05T12:46:54.670 回答