我在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中做到这一点
答案 0 :(得分:0)
API 22中没有NotificationChannel。该功能仅在API> = 26中可用。
答案 1 :(得分: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 repo