Невозможно получить атрибут темы из контекста BroadcastReceiver - PullRequest
0 голосов
/ 09 марта 2020

Я пытаюсь получить ?colorSecondary в моем BroadcastReceiver, чтобы я мог установить цвет значка уведомления и текста действия. Я использую следующий метод для получения значения моего 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);

Теперь проблема в том, что я получаю false результат от resolveAttribute() вызова. Похоже, что контекст, предоставленный BroadcastReceiver, не может найти colorSecondary. Как получить нужный атрибут из контекста BroadcastReceiver?

1 Ответ

0 голосов
/ 09 марта 2020

В отличие от Activity, BroadcastReceiver не предоставляет контекст с темой, поскольку это не-пользовательский контекст. Итак, атрибуты темы деятельности здесь недоступны. Вы можете попытаться установить тему вручную в этом контексте следующим образом, чтобы получить 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;
}
...