关于在Android 12上面自定义通知View点击按钮无响应问

2023-01-08  本文已影响0人  伪装的狼

在开发自定义通知消息的时候,有个需求是点击通知消息的关闭按钮实现隐藏消息通知。设置通知PendingIntent的代码如下:

val closePendingIntent: PendingIntent = PendingIntent.getBroadcast(
    context,
    0,
    Intent("demo.notice.msg"),
    PendingIntent.FLAG_IMMUTABLE
)

注册广播

<receiver android:name=".NoticeBroadcastReceiver"  android:exported="false">
    <intent-filter>
        <action android:name="demo.notice.msg"/>
    </intent-filter>
</receiver>

广播接收

class NoticeBroadcastReceiver: BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(100)
    }

}

发现在Android 7.0、Android 10上面NoticeBroadcastReceiver可以正常接收广播,并且正常取消通知消息。而在Android 12的小米系统上面运行NoticeBroadcastReceiver没有接收到消息事件。后面多次测试排查发现,设置PendingIntent的Intent需要指定ComponentName,随后PendingIntent代码改为即可:

val closePendingIntent: PendingIntent = PendingIntent.getBroadcast(
    context,
    0,
    Intent(context, NoticeBroadcastReceiver::class.java).apply {
        action = "demo.notice.msg"
    },
    PendingIntent.FLAG_IMMUTABLE
)

适配Android 13通知

清单文件加入通知权限即可

<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
上一篇下一篇

猜你喜欢

热点阅读