如何解决Android SDK 34下PendingIntent未指定FLAG的异常问题
解决NativeScript中com.telerik.localnotifications库的PendingIntent异常问题
你的异常是因为Android 12(API 31)及以上版本强制要求创建PendingIntent时必须指定FLAG_IMMUTABLE或FLAG_MUTABLE标记,但你依赖的com.telerik.localnotifications库内部代码没做这个适配——从堆栈信息能看到,问题出在NotificationRestoreReceiver调度通知时,Builder.applyTapReceiver方法创建PendingIntent的环节。
给你三个层级的解决方法,按优先级排序:
1. 升级库到最新版本
这是最稳妥的方案,官方大概率已经在后续版本中修复了Android 12+的适配问题。执行以下命令更新:
npm install nativescript-local-notifications@latest --save
更新完后清理项目缓存并重新构建:
ns clean && ns build android
2. 手动修改库源码(如果最新版没修复)
如果升级后问题还在,直接修改node_modules里的库代码:
- 找到文件:
node_modules/nativescript-local-notifications/platforms/android/java/com/telerik/localnotifications/Builder.java - 定位到
applyTapReceiver方法(对应堆栈第187行),找到创建PendingIntent.getService的代码 - 添加
FLAG_IMMUTABLE标记(通知点击场景推荐用这个,符合官方最佳实践):
原代码类似:
修改为兼容多版本的代码:PendingIntent pendingIntent = PendingIntent.getService(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);int flags = PendingIntent.FLAG_UPDATE_CURRENT; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { flags |= PendingIntent.FLAG_IMMUTABLE; } PendingIntent pendingIntent = PendingIntent.getService(context, requestCode, intent, flags); - 同样检查
NotificationRestoreReceiver.java里创建PendingIntent的代码,确保也加上了相同的标记 - 修改完成后重新构建项目:
ns build android
3. 用patch-package持久化修改(避免npm install覆盖)
手动改源码的问题是每次npm install都会被覆盖,用patch-package可以把修改保存成补丁,自动应用:
- 安装依赖:
npm install patch-package --save-dev - 修改完库源码后,生成补丁:
npx patch-package nativescript-local-notifications - 之后每次执行
npm install,补丁都会自动生效,不用重复改代码
注意事项
- 除非你的应用需要内回复、气泡这类依赖可变
PendingIntent的功能,否则一律用FLAG_IMMUTABLE,这是Android官方强烈推荐的选项 - 优先用方案1,官方维护的版本兼容性和稳定性都更好
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

