Android 11 个显示指标

Android 11 DisplayMetrics

Android11.

的另一个重大变化
 Caused by: java.lang.UnsupportedOperationException: Tried to obtain display from a Context not associated with  one. Only visual Contexts (such as Activity or one created with Context#createWindowContext) or ones created with Context#createDisplayContext are associated with displays. Other types of Contexts are typically related to background entities and may return an arbitrary display.

我有一个自定义的RecyclerView,这是错误发生时的流程。

public AutoPlayVideoRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

private void initView(Context context) {
        heightScreen = getHeightScreen(context); ...


private int getHeightScreen(Context context) {
        return RealDisplayMetricsUtil.getDeviceRealHeight(context);
    }

public class RealDisplayMetricsUtil {

    public static int getDeviceRealHeight(Context context){
        DisplayMetrics displayMetrics = new DisplayMetrics();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
            context.getDisplay().getRealMetrics(displayMetrics);
        else {
            WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            windowManager.getDefaultDisplay().getRealMetrics(displayMetrics);
        }
        return displayMetrics.heightPixels;
    }

错误从这里开始

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
            context.getDisplay().getRealMetrics(displayMetrics);

我认为上面的代码没有任何不同,因为两者都在 Android SDK 31 中被弃用,因此我只是完全删除了条件以解决问题。这不是最终答案,但它应该暂时有效。有空在这里添加新的解决方案,我会在审核和测试后标记为答案。

DisplayMetrics displayMetrics = new DisplayMetrics();

        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getRealMetrics(displayMetrics);
        return displayMetrics.heightPixels;