如何解决androidapi30+中的“缺少PendingIntent可变性标志”lint警告?
只要我的目标更新SDK至30(安卓R),棉绒警告Missing PendingIntent mutability flag出现在我的PendingIntent.FLAG_UPDATE_CURRENT标志时,我想定义PendingIntent。
我应该如何处理这个 lint 而不影响应用程序功能?
回答
如果您使用的不是最新版本的 WorkManager,您将看到此问题。它已在2.7.0-alpha02版本中修复:
明确 PendingIntent 可变性,以修复面向 Android 12 时的崩溃
请记住,2.7.0-alpha02 仅与 Android 12 Developer Preview 1 SDK 兼容。因此,您可能要等到它达到测试版或 RC。
2021年4 月 21 日更新——为任何使用谷歌搜索该问题的人添加此答案,您可能遇到的错误可能如下所示:
java.lang.IllegalArgumentException: com.myapp.myapp: Targeting S+ (version 10000 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
at android.app.PendingIntent.checkFlags(PendingIntent.java:386)
at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:657)
at android.app.PendingIntent.getBroadcast(PendingIntent.java:644)
at androidx.work.impl.utils.ForceStopRunnable.getPendingIntent(ForceStopRunnable.java:174)
at androidx.work.impl.utils.ForceStopRunnable.isForceStopped(ForceStopRunnable.java:108)
at androidx.work.impl.utils.ForceStopRunnable.run(ForceStopRunnable.java:86)
at androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:75)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:920)
您不必实际直接在您的应用程序中使用 WorkManager 来查看此崩溃。
该解决方案所概述这里,是一个依赖添加到您的build.gradle文件为Android构建12:
implementation 'androidx.work:work-runtime-ktx:2.7.0-alpha05'
请注意,无论您是使用 Java only、Kotlin + coroutines、RxJava2、GCMNetworkManager 等,此依赖项都是不同的。 所以一定要检查上面的 dox。
显然将上面的版本号替换为最新的。如前所述,它与 android-13 之前的版本不兼容。
- 我尝试了```实现“androidx.work:work-runtime:2.7.0-alpha05”```。它与java一起工作正常。
回答
您可以将挂起的意图设置为
val updatedPendingIntent = PendingIntent.getActivity(
applicationContext,
NOTIFICATION_REQUEST_CODE,
updatedIntent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT // setting the mutability flag
)
根据这里的文档:https : //developer.android.com/about/versions/12/behavior-changes-12#pending-intent-mutability
强烈考虑使用 FLAG_IMMUTABLE,仅当某些功能依赖于 PendingIntent 是可变的时才使用 FLAG_MUTABLE,例如,如果它需要与内联回复或气泡一起使用。
相应地选择您的标志。
如果您想阅读更多相关信息,我建议您在此处阅读这篇很棒的文章:https : //medium.com/androiddevelopers/all-about-pendingintents-748c8eb8619