Android应用后台/清除时通知点击失效及锁屏跳转需求求助
问题解决方法
核心原因分析
- Android 11(API 30)及以上版本对静态广播接收器的后台触发做了严格限制,同时禁止无用户交互的后台Activity启动,导致原
PendingIntent.getBroadcast方案失效。 - 原
PendingIntent.getActivity方案锁屏要求输入PIN,是因为未配置Activity的锁屏显示权限及通知渠道的可见性设置。
步骤1:替换PendingIntent实现(弃用BroadcastReceiver)
修改NotificationUtils.kt中的getViewPendingIntent方法,直接使用PendingIntent.getActivity,并适配高版本SDK的PendingIntent flag要求:
import android.os.Build // ... 其他代码保持不变 private fun getViewPendingIntent(context: Context, typeViewCode: Int): PendingIntent { val viewIntent = Intent(context, NotificationMainActivity::class.java) viewIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK // 适配Android 12+的PendingIntent flag要求 val pendingFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE } else { PendingIntent.FLAG_UPDATE_CURRENT } return PendingIntent.getActivity(context, typeViewCode, viewIntent, pendingFlags) }
步骤2:配置NotificationMainActivity的锁屏权限
在AndroidManifest.xml中给NotificationMainActivity添加锁屏相关属性,允许其直接在锁屏显示:
<activity android:name=".ui.NotificationMainActivity" android:showWhenLocked="true" android:showOnLockScreen="true" android:turnScreenOn="true" android:exported="true" />
showWhenLocked:允许Activity在锁屏状态下显示showOnLockScreen:允许Activity在安全锁屏(如PIN/图案锁)上显示turnScreenOn:点击通知时自动点亮屏幕
步骤3:调整通知渠道及通知配置
- 修改通知渠道的可见性和优先级,确保锁屏下通知可交互:
在NotificationUtils.kt的createChannels方法中:
private fun createChannels() { val androidChannel = NotificationChannel( ANDROID_CHANNEL_ID, ANDROID_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH // 提升优先级,确保锁屏可见 ) androidChannel.enableLights(true) androidChannel.enableVibration(true) androidChannel.lightColor = Color.GREEN androidChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC // 设为PUBLIC,允许锁屏显示通知内容及交互 manager!!.createNotificationChannel(androidChannel) }
- 确认通知Builder的优先级配置:
private fun getAndroidChannelNotification(context: Context): NotificationCompat.Builder { return NotificationCompat.Builder(applicationContext, ANDROID_CHANNEL_ID) .setSmallIcon(R.drawable.ic_logo_for_notification) .setOngoing(true) .setPriority(NotificationCompat.PRIORITY_HIGH) // 与渠道优先级匹配 .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.notification_pull_down_information)) .setShowWhen(false) .setColor(Color.BLACK) .setAutoCancel(true) .setContent(getCustomNotificationView(context)) .setStyle(NotificationCompat.DecoratedCustomViewStyle()) }
步骤4:移除无用代码
- 删除
NotificationReceiver.kt文件 - 删除
AndroidManifest.xml中的<receiver>声明
关键说明
- 高版本SDK中,通知点击属于用户主动交互,使用
PendingIntent.getActivity符合后台启动Activity的规则,不会被系统拦截。 - 锁屏直接打开Activity的核心是配置Activity的
showWhenLocked/showOnLockScreen属性,同时将通知渠道可见性设为PUBLIC,避免系统要求解锁。
内容的提问来源于stack exchange,提问作者Rabindra Acharya
相关产品推荐
相关产品推荐

