gpt4 book ai didi

java - 如何创建 Android 通知?

转载 作者:行者123 更新时间:2023-12-02 00:40:18 25 4
gpt4 key购买 nike

我正在尝试创建一个不需要在用户屏幕上弹出的通知,但我需要将其显示在通知栏中。请告诉我以下代码有什么问题,因为它没有输出任何通知:

    Intent notificationIntent = new Intent(this, ToDoList.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Title")
.setContentIntent(pendingIntent)
.setContentText("Notification text");

Notification notification = builder.build();

NotificationManager notificationManager =
(NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIF_ID, notification);

最佳答案

我使用下面的 func 创建一个简单的通知(它是用 Kotlin 编写的)

private fun showNotification(context: Context, title: String, body: String) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
val mChannel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(mChannel)
}

val notificationBuilder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)

val stackBuilder = TaskStackBuilder.create(context)
val resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
notificationBuilder.setContentIntent(resultPendingIntent)
notificationManager.notify(notificationId, notificationBuilder.build())
}

关于java - 如何创建 Android 通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57946290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com