根据
Android开发者网站所述:
从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)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true);
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());
}
Kotlin:
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)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
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())
}
注意: 如果您想显示悬浮通知,您可以将您的通道和通知重要性设置为高,并且卸载您的应用并重新安装。
Android 13+ 上的更新:
如果您想在 Android 13+ 上发布显示通知,则需要从用户那里获取运行时权限。要获取权限,请将此行添加到您的 AndroidManifest.xml
文件中:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
在您的应用程序中,您可以像这样获取权限:
private fun getNotificationPermission() {
if (VERSION.SDK_INT >= VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 100)
}
}