package com.ttstd.dialer.utils; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.util.Log; import java.lang.reflect.Method; public class ScreenUtils { private static final String TAG = "ScreenUtils"; /** * 根据手机的分辨率从 dp 的单位 转成为 px(像素) */ public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */ public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } public static int dp2px(Resources resources, float dp) { final float scale = resources.getDisplayMetrics().density; return (int) (dp * scale + 0.5f); } public static int sp2px(Resources resources, float sp) { final float scale = resources.getDisplayMetrics().scaledDensity; return (int) (sp * scale); } /** * 应用需反射调用 */ public static boolean isTablet() { try { // 1. 反射获取 SystemProperties 类 Class systemPropertiesClass = Class.forName("android.os.SystemProperties"); // 2. 获取 get(String key) 方法 Method getMethod = systemPropertiesClass.getDeclaredMethod("get", String.class); // 3. 调用方法获取属性值 String characteristics = (String) getMethod.invoke(null, "ro.build.characteristics"); Log.e(TAG, "isTablet: " + characteristics); // 4. 判断是否包含 "tablet" 标识 return characteristics != null && characteristics.contains("tablet"); } catch (Exception e) { // 反射失败时的处理(如属性不存在或权限问题) Log.e(TAG, "Reflection failed: " + e.getMessage()); return false; } } public static boolean isTablet(Context context) { boolean isTablet = (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; Log.e(TAG, "isTablet: " + isTablet); return isTablet; } /** * 是否是平板 * * @param context 上下文 * @return 是平板则返回true,反之返回false */ public static boolean isPad(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; } }