主活动无法启动,原因是PendingIntent标志错误。

4

我正在开发一个系统应用,在 Android 31 中尝试从主屏幕启动应用时失败了,并抛出了 java.lang.IllegalArgumentException。下面是堆栈跟踪信息:

java.lang.IllegalArgumentException: tech.[brand].[name]: Targeting S+ (version 31 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:375)
        at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:645)
        at android.app.PendingIntent.getBroadcast(PendingIntent.java:632)
        at androidx.work.impl.utils.ForceStopRunnable.getPendingIntent(ForceStopRunnable.java:285)
        at androidx.work.impl.utils.ForceStopRunnable.isForceStopped(ForceStopRunnable.java:158)
        at androidx.work.impl.utils.ForceStopRunnable.forceStopRunnable(ForceStopRunnable.java:185)
        at androidx.work.impl.utils.ForceStopRunnable.run(ForceStopRunnable.java:103)
        at androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:91)
        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)

栈并没有到达我的任何源代码,据我所知我目前还没有在代码中调用任何待处理或其他意图。有人知道发生了什么吗?

2个回答

4
androidx.work在堆栈跟踪中指的是WorkManager。根据WorkManager 2.7.0-alpha02的说明:

明确 PendingIntent 的可变性,以解决针对 Android 12 的崩溃问题。

因此,您应该将最新版本的WorkManager 2.7.1添加到build.gradle文件的dependencies块中,以显式地依赖于该最新版本。
implementation "androidx.work:work-runtime:2.7.1"

我的版本设置为2.6.0。刚刚解决了几个小时的问题,真是救星! - j_wash_BL
我正在使用实现 "androidx.work:work-runtime:2.7.1",但应用在三星设备上一直崩溃。 - Dreamer
我的应用在 Android 模拟器 API 31+ 上崩溃,而且没有记录任何信息。这个方法解决了问题。很高兴我找到了它。 - user1608385

0

PendingIntent 是 API 21+ 中的一个标志。因此,您可以像这样设置它:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
  PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
} 
else {
 PendingIntent.FLAG_UPDATE_CURRENT 
}

OR

根据这里的文档,应该选择FLAG_IMMUTABLE。如果某些功能依赖于PendingIntent,则使用FLAG_MUTABLE

val updatedPendingIntent = PendingIntent.getActivity(
   applicationContext,
   NOTIFICATION_REQUEST_CODE,
   updatedIntent,
   PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT // setting the mutability flag 
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接