Search code examples
androidbroadcastreceiverandroid-theme

Unable to get theme attribute from BroadcastReceiver's context


I am trying to get ?colorSecondary in my BroadcastReceiver, so that I can set colour to notification icon and action text. I am using following method to get value of my R.attr.colorSecondary from my current theme.

@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);

Now the problem is, I am getting false result from resolveAttribute() call. Looks like the context provided by BroadcastReceiver is not able to find colorSecondary. How to get the desired attribute from BroadcastReceiver's context?


Solution

  • Unlike Activity, BroadcastReceiver does not provide context with a theme, as it is a non-UI context. So, attributes of activity's theme are not available here. You can try to set the theme manually to this context, as follows, to get 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;
    }