如Android developers website中所述:
从 Android 8.0(API 级别 26)开始,所有通知都必须是
分配给一个频道。对于每个通道,您可以设置视觉和
应用于所有通知的听觉行为
渠道。然后,用户可以更改这些设置并决定哪些
您的应用程序的通知渠道应该是侵入性的或可见的
全部。
所以您可以使用此方法在 -27 和 +27 api 中显示通知:
Java:
void showNotification(String title, String message) {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("YOUR_CHANNEL_ID",
"YOUR_CHANNEL_NAME",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("YOUR_NOTIFICATION_CHANNEL_DESCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), "YOUR_CHANNEL_ID")
.setSmallIcon(R.mipmap.ic_launcher) // notification icon
.setContentTitle(title) // title for notification
.setContentText(message)// message for notification
.setAutoCancel(true); // clear notification after click
Intent intent = new Intent(getApplicationContext(), ACTIVITY_NAME.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
mNotificationManager.notify(0, mBuilder.build());
}
科特林:
fun showNotification(title: String, message: String) {
val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
val channel = NotificationChannel("YOUR_CHANNEL_ID",
"YOUR_CHANNEL_NAME",
NotificationManager.IMPORTANCE_DEFAULT)
channel.description = "YOUR_NOTIFICATION_CHANNEL_DESCRIPTION"
mNotificationManager.createNotificationChannel(channel)
}
val mBuilder = NotificationCompat.Builder(applicationContext, "YOUR_CHANNEL_ID")
.setSmallIcon(R.mipmap.ic_launcher) // notification icon
.setContentTitle(title) // title for notification
.setContentText(message)// message for notification
.setAutoCancel(true) // clear notification after click
val intent = Intent(applicationContext, ACTIVITY_NAME::class.java)
val pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
mBuilder.setContentIntent(pi)
mNotificationManager.notify(0, mBuilder.build())
}
注意:如果您想显示提醒通知,您可以将您的频道和通知的重要性设置为高,并删除您的应用并安装它再次。