You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android API 31下WorkManager调用createCancelPendingIntent报PendingIntent flag错误

问题根因与解决方案

异常触发说明

你遇到的是Android 12(API 31+)专属的PendingIntent合规异常:

Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent

该异常在调用WorkManager.getInstance(context).createCancelPendingIntent(id)时触发。

根因验证

你的推测完全正确,问题确实出在BuildCompat.isAtLeastS()的判断逻辑上:

/**
 * Checks if the device is running on a pre-release version of Android S or a release version of
 * Android S or newer.
 * <p>
 * <strong>Note:</strong> When Android S is finalized for release, this method will be
 * deprecated and all calls should be replaced with {@code Build.VERSION.SDK_INT >=
 * Build.VERSION_CODES.S}.
 *
 * @return {@code true} if S APIs are available for use, {@code false} otherwise
 */
@ChecksSdkIntAtLeast(codename = "S")
public static boolean isAtLeastS() {
    return VERSION.CODENAME.equals("S");
}

正式发布的Android 12系统版本代号为REL,只有预览版Android S的代号才是S,所以在API 31正式版模拟器上该判断返回false,你使用的2.7.0-alpha05版本WorkManager依赖该方法判断系统版本,没有给PendingIntent添加S+要求的FLAG,最终抛出异常。

解决方案

  • 升级WorkManager依赖版本:将androidx.work:work-runtime-ktx升级到2.7.1及以上的正式稳定版即可,该版本已经将版本判断逻辑替换为Build.VERSION.SDK_INT >= Build.VERSION_CODES.S,完全兼容正式版Android 12的版本校验。
  • Build Tools 31.0.0损坏问题:可以直接升级到31.0.0以上的Build Tools版本(如32.0.0、33.0.2),不需要降级到30.0.3,也能正常编译。

内容的提问来源于stack exchange,提问作者iClaude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 18:12:03