Android 获取屏幕物理尺寸

注:编译 sdk 需要使用 30

因为引入了 WindowMetrics、uild.VERSION_CODES.R 新 sdk 才存在的类和属性

某些场景处理 view ,对 view 显示的位置要求比较精确,通常我们使用context.getResources().getDisplayMetrics().widthPixels 获取到的宽、高是不包含状态栏等高度,在计算坐标、偏移量时可能就不精确了,那么就需要获取设备的物理尺寸——包含状态栏高度等不显示区域。

import android.graphics.Point;
import android.graphics.Rect;
import android.util.Pair;
import android.util.Size;
import android.view.WindowManager;
import android.view.WindowMetrics;

import androidx.annotation.RequiresApi;

@RequiresApi(api = Build.VERSION_CODES.R)
private static Size getPhysicalScreenSize30(Context context) {
    WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    if (windowManager != null) {
        WindowMetrics windowMetrics = windowManager.getCurrentWindowMetrics();
        Rect bounds = windowMetrics.getBounds();
        return new Size(bounds.width(), bounds.height());
    }
    return new Size(-1,-1);
}

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static Size getPhysicalScreenSize29(Context context) {
    WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    if (windowManager != null) {
        Point size = new Point();
        windowManager.getDefaultDisplay().getRealSize(size);
        return new Size(size.x, size.y);
    }
    return new Size(-1,-1);
}

public static Pair<Integer, Integer> getPhysicalScreenSize(Context context) {
    int w = -1, h = -1;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        Size size = getPhysicalScreenSize30(context);
        w = size.getWidth();
        h = size.getHeight();
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Size size = getPhysicalScreenSize29(context);
            w = size.getWidth();
            h = size.getHeight();
        }
    }

    if (w != -1 && h != -1) {
        return new Pair<>(w, h);
    }

    //最不济的情况就返回非物理尺寸吧
    w = context.getResources().getDisplayMetrics().widthPixels;
    h = context.getResources().getDisplayMetrics().heightPixels;
    return new Pair<>(w, h);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值