Search code examples
androidandroid-11

Android 11 DisplayMetrics


Another breaking changes from Android 11.

 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.

I have a custom RecyclerView and this is the flow when the error occurred.

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;
    }

The error started here

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

Solution

  • I don't think the code above makes any different since both are deprecated in Android SDK 31, thus I just removed the condition completely to fix the issue. This is not the final answer but it should work for a meantime. Free to add new solution here, I will mark it as the answer after reviewing and testing it.

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