我的应用程序使用接收器在一定时间后向用户发送通知。接收器运行得很好,因为它运行了一些功能,但通知工作得不太顺利。
在模拟器(API29和Android 10)上,它会正确发送它们,但当我将其安装在真实设备上时,它要么根本不工作,要么工作得非常好。
我的手机有完美的通知,直到当我更新到android12,从那时起没有任何通知发射.我也测试了它在旧设备(android7),再次它不工作.
我读了它,并不真正了解如何通道的工作,所以我认为问题可能是存在的,但我觉得奇怪的是,它将如何仍然在一些设备/模拟器上工作。
下面是我的代码:
class MyReceiver: BroadcastReceiver() {
@RequiresApi(Build.VERSION_CODES.O)
override fun onReceive(context: Context, intent: Intent) {
val notificationChannel =
NotificationChannel("My Channel", "New Quote",
NotificationManager.IMPORTANCE_DEFAULT).apply {
description = "Alerts when A new daily quote is set!"
}
val titles = arrayOf(
"Become inspired!",
"Check out this quote!",
"A new quote appeared!",
"Daily quote available!"
)
val title = titles.random()
val i = Intent(context, Qinperation::class.java)
val builder = NotificationCompat.Builder(context, "My Channel")
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle(title)
.setContentText("A new daily quote is available for viewing")
.setContentIntent(
PendingIntent.getActivity(
context,
0,
i,
PendingIntent.FLAG_UPDATE_CURRENT
)
);
with(NotificationManagerCompat.from(context)) {
createNotificationChannel(notificationChannel)
notify(1, builder.build())
}
}
}
感谢所有的帮助:)
1条答案
按热度按时间cbjzeqam1#
安卓O及以上版本需要通道。你需要在收到通知之前创建通道。通道基本上就像一个“开关”,可以从应用程序的设置中关闭和打开,你可以配置你的通知,这意味着你可以配置如果你收到通知,如果它应该振动等。
在Android版本O之前,您不需要通道,通知的配置是从notificationBuilder中进行的。
因此,如果你想配置你的通知以上和以下版本的O你必须这样做的两个地方。
现在关于您的问题,我认为您最迟创建通道,并在第一个Activity或应用程序类中调用此方法:
然后在接收器中,您只需创建通知并调用以下命令:
如果这不起作用,你可能想添加一个日志,看看你的接收器是否真的被调用。