无法从 BroadcastReceiver 的上下文中获取主题属性

Unable to get theme attribute from BroadcastReceiver's context

我正在尝试在我的 BroadcastReceiver 中获取 ?colorSecondary,以便我可以为通知图标和操作文本设置颜色。我正在使用以下方法从当前主题中获取 R.attr.colorSecondary 的价值。

@ColorRes
public static int getAttrColorResId(Context context, @AttrRes int resId) {
    TypedValue outValue = new TypedValue();
    Resources.Theme theme = context.getTheme();
    boolean success = theme.resolveAttribute(resId, outValue, true);    
    return outValue.resourceId;
}

// usage 
int colorRes = getAttrColorResId(context, R.attr.colorSecondary);

现在的问题是,我从 resolveAttribute() 调用中得到 false 结果。看起来 BroadcastReceiver 提供的上下文无法找到 colorSecondary。如何从 BroadcastReceiver 的上下文中获取所需的属性?

与 Activity 不同,BroadcastReceiver 不提供主题上下文,因为它是非 UI 上下文。因此,activity 的主题属性在这里不可用。可以尝试手动设置主题到这个上下文,如下,得到colorSecondary:

@ColorRes
public static int getAttrColorResId(Context context, @AttrRes int resId) {
    TypedValue outValue = new TypedValue();
    Resources.Theme theme = context.getTheme();
    boolean success = theme.resolveAttribute(resId, outValue, true);

    // if not success, that means current call is from some non-UI context 
    // so set a theme and call recursively
    if (!success) {
        context.getTheme().applyStyle(R.style.YourTheme, false);
        return getAttrColorResId(context, resId);
    }

    return outValue.resourceId;
}