Wear OS中Complication因PendingIntent标记缺失引发崩溃问题
Wear OS API31+ 点击Complication崩溃问题解决
问题根源
从崩溃栈可以明确看出:崩溃不是你代码里getToggleIntent方法的问题,而是旧版android.support.wearable.complications.ProviderUpdateRequester内部创建PendingIntent时,没有添加API31+要求的FLAG_IMMUTABLE或FLAG_MUTABLE标记。你自己添加的Flag只覆盖了点击Complication的PendingIntent,但更新Complication请求内部的PendingIntent未适配新系统规则。
解决办法
方案一:升级到Jetpack Wear Complications库(推荐)
旧的support库已停止维护,无法适配新系统要求,直接迁移到Jetpack版本:
- 更新gradle依赖,引入最新的Wear Complications相关库:
implementation "androidx.wear:wear-complications-data:1.0.1" implementation "androidx.wear:wear-complications-provider:1.0.1"
- 替换代码中的导入语句:
把原有的import android.support.wearable.complications.ProviderUpdateRequester;替换为:
import androidx.wear.complications.provider.ProviderUpdateRequester;
- 原
initComplications方法无需修改,Jetpack版本的ProviderUpdateRequester已内部处理API31+的PendingIntent Flag要求。
方案二:手动实现Complication更新请求(无需升级库)
若暂时不想升级依赖,可自行编写代码替代ProviderUpdateRequester的功能,手动创建符合要求的PendingIntent:
修改IndicatorComplicationTapBroadcastReceiver中的initComplications方法:
public void initComplications(Context c) { Log.i(TAG5, "started initComplications()"); ComponentName componentName1 = new ComponentName(c, IndicatorCounterComplicationProviderService.class); // 构建更新Complication的Intent Intent updateIntent = new Intent(ComplicationProviderService.ACTION_UPDATE_COMPLICATIONS); updateIntent.putExtra(ComplicationProviderService.EXTRA_PROVIDER_COMPONENT, componentName1); updateIntent.setPackage(c.getPackageName()); // 安全限制包名 // 根据API版本设置正确的Flag int pendingIntentFlags; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { pendingIntentFlags = PendingIntent.FLAG_IMMUTABLE; } else { pendingIntentFlags = 0; // 旧版本无需特殊Flag } // 创建并发送PendingIntent PendingIntent pendingIntent = PendingIntent.getBroadcast(c, 0, updateIntent, pendingIntentFlags); try { pendingIntent.send(); } catch (PendingIntent.CanceledException e) { Log.e(TAG5, "Failed to trigger complication update", e); } }
额外检查
确保getToggleIntent方法中使用的是正确的Flag常量,导入的是android.app.PendingIntent:
import android.app.PendingIntent;
效果验证
修改完成后,在API31及以上的Wear OS设备测试:
- 点击Complication不再崩溃
- 计数器数值能正常更新并显示在Complication上
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

