use*_*119 3 android kotlin android-studio
我正在使用 Kotlin 和 Android Studio 尝试在测试应用程序中推送通知。我按照 Android 开发人员网站上有关如何创建通知的说明进行操作(https://developer.android.com/training/notify-user/build-notification),但我似乎做错了什么,因为我的通知没有显示任何地方。这是我的代码:
val intent = Intent(context, Profile::class.java)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0);
val builder = NotificationCompat.Builder(this.context)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_MAX)
builder.setContentIntent(pendingIntent).setAutoCancel(true)
val mNotificationManager = message.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
with(mNotificationManager) {
notify(123, builder.build())
Run Code Online (Sandbox Code Playgroud)
我真的不知道我错过了什么,所以我将不胜感激任何帮助。
根据您的代码,您没有创建通知通道。
Android Oreo及以上版本需要通知通道
因此,如果您在没有通知通道的情况下运行应用程序 Android O 及更高版本的设备,您的通知将不会显示。
fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "all_notifications" // You should create a String resource for this instead of storing in a variable
val mChannel = NotificationChannel(
channelId,
"General Notifications",
NotificationManager.IMPORTANCE_DEFAULT
)
mChannel.description = "This is default channel used for all other notifications"
val notificationManager =
mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
}
Run Code Online (Sandbox Code Playgroud)
然后在创建通知时使用相同的channelId创建通知。
createNotificationChannel()
val channelId = "all_notifications" // Use same Channel ID
val intent = Intent(context, Profile::class.java)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0);
val builder = NotificationCompat.Builder(this.context, channelId) // Create notification with channel Id
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_MAX)
builder.setContentIntent(pendingIntent).setAutoCancel(true)
val mNotificationManager =
message.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
with(mNotificationManager) {
notify(123, builder.build())
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你。
归档时间: |
|
查看次数: |
8622 次 |
最近记录: |