96

有没有办法以编程方式查找安装应用程序的设备是 7 英寸平板电脑还是 10 英寸平板电脑?

4

13 回答 13

239

您可以使用DisplayMetrics获取有关您的应用程序正在运行的屏幕的大量信息。

首先,我们创建一个DisplayMetrics度量对象:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

从中,我们可以获得显示大小所需的信息:

int widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;

这将返回宽度和高度的绝对值(以像素为单位),因此 Galaxy SIII、Galaxy Nexus 等为 1280x720。

这本身通常没有帮助,因为当我们在 Android 设备上工作时,我们通常更喜欢在与密度无关的像素中工作,dip。

您再次以设备比例因子的形式获得density屏幕的,metrics它基于Android 设计资源等。 mdpihdpiDPI 刻度

float scaleFactor = metrics.density;

从这个结果中,我们可以计算出在某个高度或宽度下与密度无关的像素的数量。

float widthDp = widthPixels / scaleFactor
float heightDp = heightPixels / scaleFactor

从中获得的结果将帮助您确定正在使用的屏幕类型以及Android 配置示例,它为您提供每种屏幕尺寸的相对 dp:

  • 320dp:典型的手机屏幕(240x320 ldpi、320x480 mdpi、480x800 hdpi 等)。
  • 480dp:像 Streak (480x800 mdpi) 这样的补间平板电脑。
  • 600dp:7 英寸平板电脑 (600x1024 mdpi)。
  • 720dp:10 英寸平板电脑(720x1280 mdpi、800x1280 mdpi 等)。

通过以上信息,我们知道如果设备的最小宽度大于 600dp,则该设备为 7" 平板电脑,如果大于 720dp,则该设备为 10" 平板电脑。

我们可以使用 class 的min函数计算出最小宽度Math,传入 theheightDp和 thewidthDp以返回smallestWidth.

float smallestWidth = Math.min(widthDp, heightDp);

if (smallestWidth > 720) {
    //Device is a 10" tablet
} 
else if (smallestWidth > 600) {
    //Device is a 7" tablet
}

然而,这并不总是给你一个精确的匹配,尤其是在使用不起眼的平板电脑时,这些平板电脑可能会将其密度错误地表示为 hdpi 而不是,或者可能只有 800 x 480 像素但仍然在 7" 屏幕上.

除了这些方法之外,如果您需要知道设备的确切尺寸(以英寸为单位),您也可以使用该metrics方法计算出每英寸屏幕有多少像素。

float widthDpi = metrics.xdpi;
float heightDpi = metrics.ydpi;

您可以使用每英寸设备中有多少像素以及总像素量的知识来计算设备的英寸数。

float widthInches = widthPixels / widthDpi;
float heightInches = heightPixels / heightDpi;

这将以英寸为单位返回设备的高度和宽度。这对于确定它是什么类型的设备并不总是那么有帮助,因为设备的广告尺寸是对角线,我们所拥有的只是高度和宽度。

但是,我们也知道,给定三角形的高度和宽度,我们可以使用勾股定理计算出斜边的长度(在这种情况下,是屏幕对角线的大小)。

//a² + b² = c²

//The size of the diagonal in inches is equal to the square root of the height in inches squared plus the width in inches squared.
double diagonalInches = Math.sqrt(
    (widthInches * widthInches) 
    + (heightInches * heightInches));

由此,我们可以确定该设备是否为平板电脑:

if (diagonalInches >= 10) {
    //Device is a 10" tablet
} 
else if (diagonalInches >= 7) {
    //Device is a 7" tablet
}

这就是您计算正在使用的设备类型的方式。

于 2013-02-28T10:59:47.367 回答
33

没有什么可以说7"10"AFAIK。大致有两种方法可以获得系统在解码位图时使用的屏幕尺寸等等。它们都可以ResourcesContext.

第一个是Configuration可以通过 获取的对象getContext().getResources().getConfiguration()。在里面你有:

Configuration#densityDpi- 渲染到的目标屏幕密度,对应于密度资源限定符。

Configuration#screenHeightDp- 可用屏幕空间的当前高度,以 dp 为单位,对应于屏幕高度资源限定符。

Configuration#screenWidthDp- 可用屏幕空间的当前宽度,以 dp 为单位,对应于屏幕宽度资源限定符。

Configuration#smallestScreenWidthDp- 应用程序在正常操作中看到的最小屏幕尺寸,对应于最小屏幕宽度资源限定符。

这样,您几乎可以使用屏幕指南来确定您的设备是否从相应的专用资源文件夹(hdpixhdpilargexlarge等)中提取。

请记住,这些是一些桶:

  • 超大屏幕至少为 960dp x 720dp
  • 大屏幕至少为 640dp x 480dp
  • 普通屏幕至少为 470dp x 320dp
  • 小屏幕至少为 426dp x 320dp

  • 320dp:典型的手机屏幕(240x320 ldpi、320x480 mdpi、480x800 hdpi 等)。

  • 480dp:像 Streak (480x800 mdpi) 这样的补间平板电脑。
  • 600dp:7 英寸平板电脑 (600x1024 mdpi)。
  • 720dp:10 英寸平板电脑(720x1280 mdpi、800x1280 mdpi 等)。

更多信息

二是DisplayMetrics得到的对象getContext().getResources().getDisplayMetrics()。你有:

DisplayMetrics#density- 显示的逻辑密度。

DisplayMetrics#densityDpi- 以每英寸点数表示的屏幕密度。

DisplayMetrics#heightPixels- 显示的绝对高度(以像素为单位)。

DisplayMetrics#widthPixels- 显示的绝对宽度(以像素为单位)。

DisplayMetrics#xdpi- X 维度上每英寸屏幕的精确物理像素。

DisplayMetrics#ydpi- Y 维度上每英寸屏幕的精确物理像素。

如果您需要屏幕的精确像素数而不是密度,这很方便。但是,重要的是要注意这是屏幕的所有像素。不仅仅是您可以使用的。

于 2013-02-28T10:59:22.887 回答
13

将此方法放在 onResume() 中并可以检查。

public double tabletSize() {

     double size = 0;
        try {

            // Compute screen size

            DisplayMetrics dm = context.getResources().getDisplayMetrics();

            float screenWidth  = dm.widthPixels / dm.xdpi;

            float screenHeight = dm.heightPixels / dm.ydpi;

            size = Math.sqrt(Math.pow(screenWidth, 2) +

                                 Math.pow(screenHeight, 2));

        } catch(Throwable t) {

        }

        return size;

    }

通常平板电脑在 6 英寸大小后开始。

于 2013-02-28T11:06:04.823 回答
8

在切换纵向与横向时,上述内容并不总是有效。

如果您的目标是 API 级别 13+,如上所述很容易 - 使用 Configuration.smallestScreenWidthDp,然后进行相应的测试:

resources.getConfiguration().smallestScreenWidthDp

否则,如果您负担得起,请使用以下方法,通过让系统告诉您,这是一种非常准确的方法来检测 600dp(如 6")与 720dp(如 10"):

1)添加到 layout-sw600dp 和 layout-sw720dp (如果适用,它的横向)具有适当 ID 的不可见视图,例如:

对于 720,在 layout-sw720dp 上:

<View android:id="@+id/sw720" android:layout_width="0dp" android:layout_height="0dp" android:visibility="gone"/>

对于 600,在 layout-sw600dp 上:

<View android:id="@+id/sw600" android:layout_width="0dp" android:layout_height="0dp" android:visibility="gone"/>

2)然后在代码上,例如Activity,进行相应的测试:

private void showFragment() {
    View v600 = (View) findViewById(R.id.sw600);
    View v720 = (View) findViewById(R.id.sw720);
    if (v600 != null || v720 !=null)
        albumFrag = AlbumGridViewFragment.newInstance(albumRefresh);
    else
        albumFrag = AlbumListViewFragment.newInstance(albumRefresh);
    getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.view_container, albumFrag)
        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
        .commit();
}
于 2014-02-08T16:23:55.107 回答
7

很棒的信息,正是我想要的!但是,在尝试了这个之后,我发现使用此处提到的指标时,Nexus 7(2012 型号)报告的尺寸为 1280x736。我还有一个运行 Jelly Bean 的摩托罗拉 Xoom,它错误地报告了 1280x752 的分辨率。我在这里偶然发现了这篇文章,证实了这一点。基本上,在 ICS/JB 中,使用上述指标的计算似乎排除了导航栏的尺寸。更多的研究使我找到了 Frank Nguyen 的答案,该答案使用不同的方法为您提供屏幕的原始(或真实)像素尺寸。我的初步测试表明,来自 Frank correclty 的以下代码报告了 Nexus 7(运行 JB 的 2012 型号)和运行 JB 的摩托罗拉 Xoom 上的尺寸:

int width = 0, height = 0;
final DisplayMetrics metrics = new DisplayMetrics();
Display display = getWindowManager().getDefaultDisplay();
Method mGetRawH = null, mGetRawW = null;

try {
    // For JellyBeans and onward
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
        display.getRealMetrics(metrics);

        width = metrics.widthPixels;
        height = metrics.heightPixels;
    } else {
        mGetRawH = Display.class.getMethod("getRawHeight");
        mGetRawW = Display.class.getMethod("getRawWidth");

        try {
            width = (Integer) mGetRawW.invoke(display);
            height = (Integer) mGetRawH.invoke(display);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
} catch (NoSuchMethodException e3) {
    e3.printStackTrace();
}
于 2013-08-23T16:26:28.063 回答
3

我有两个分辨率相同的安卓设备

Device1 -> 分辨率 480x800 屏幕对角线尺寸 -> 4.7 英寸

Device2 -> 分辨率 480x800 屏幕对角线尺寸 -> 4.0 英寸

它提供了两个设备对角线屏幕尺寸 -> 5.8

你的问题的解决方案是..

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width=dm.widthPixels;
int height=dm.heightPixels;
int dens=dm.densityDpi;
double wi=(double)width/(double)dens;
double hi=(double)height/(double)dens;
double x = Math.pow(wi,2);
double y = Math.pow(hi,2);
double screenInches = Math.sqrt(x+y);

在这里查看详细信息..

于 2014-06-13T06:40:18.790 回答
3

Android 指定屏幕尺寸的方式是通过四种通用尺寸:smallnormallargexlarge

虽然 Android文档指出尺寸组已被弃用

...这些尺寸组已被弃用,取而代之的是一种基于可用屏幕宽度管理屏幕尺寸的新技术。如果您正在为 Android 3.2 及更高版本进行开发,请参阅 [Declaring Tablet Layouts for Android 3.2]( hdpi (high) ~240dpi) 了解更多信息。

通常,大小限定符large指定 7" 平板电脑。大小限定符xlarge指定 10" 平板电脑:

在此处输入图像描述

在大小限定符上触发的好处是,您可以保证您的资产和代码在使用哪个资产或激活代码路径上是一致的。

要在代码中检索大小限定符,请进行以下调用:

int sizeLarge = SCREENLAYOUT_SIZE_LARGE // For 7" tablet
boolean is7InchTablet = context.getResources().getConfiguration()
    .isLayoutSizeAtLeast(sizeLarge);

int sizeXLarge = SCREENLAYOUT_SIZE_XLARGE // For 10" tablet
boolean is10InchTablet = context.getResources().getConfiguration()
    .isLayoutSizeAtLeast(sizeXLarge);
于 2014-11-25T03:42:20.887 回答
2

您可以使用以下方法获取以英寸为单位的屏幕尺寸,基于此您可以简单地检查设备是哪个平板电脑或手机。

private static double checkDimension(Context context) {

    WindowManager windowManager = ((Activity)context).getWindowManager();
    Display display = windowManager.getDefaultDisplay();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    display.getMetrics(displayMetrics);

    // since SDK_INT = 1;
    int mWidthPixels = displayMetrics.widthPixels;
    int mHeightPixels = displayMetrics.heightPixels;

    // includes window decorations (statusbar bar/menu bar)
    try
    {
        Point realSize = new Point();
        Display.class.getMethod("getRealSize", Point.class).invoke(display, realSize);
        mWidthPixels = realSize.x;
        mHeightPixels = realSize.y;
    }
    catch (Exception ignored) {}

    DisplayMetrics dm = new DisplayMetrics();
    windowManager.getDefaultDisplay().getMetrics(dm);
    double x = Math.pow(mWidthPixels/dm.xdpi,2);
    double y = Math.pow(mHeightPixels/dm.ydpi,2);
    double screenInches = Math.sqrt(x+y);
    Log.d("debug","Screen inches : " + screenInches);
    return screenInches;
}
于 2016-02-08T08:41:12.617 回答
2

我在values 文件夹中存储了一个值,它给我的屏幕是 7 英寸或 10 英寸,但我们可以使用 values 文件夹为任何设备执行此操作。

比如为不同的 2 设备创建不同的 2 值文件夹。但这件事取决于要求。

于 2017-05-07T14:09:52.703 回答
1

您必须使用DisplayMetrics类提供的数据进行一些计算。

你有 heightPixel 和 widthPixels (以像素为单位的屏幕分辨率)

您需要对角线,因为“​​英寸屏幕尺寸”总是描述对角线长度。您可以获得以像素为单位的屏幕对角线(使用 pythagore)

对角像素 = √(heightPixel² + widthPixels² )

那么您可以通过 densityDPI 值将像素值转换为英寸:

inchDiag = 对角像素 / 密度 DPI。

我希望我没有在这里犯错,请注意您从 DisplayMetrics 类中获得的值是由构造函数给出的,看起来(在极少数情况下)它们没有根据物理材料很好地设置......

这将为您提供物理屏幕尺寸,但它可能不是管理多个布局的更好方法。有关此主题的更多信息

于 2013-02-28T11:02:22.177 回答
1

其他方式:

  • 再创建 2 个文件夹:values-large + values-xlarge

  • 放入:<string name="screentype">LARGE</string>在 values-large 文件夹中(strings.xml)

  • 放入:<string name="screentype">XLARGE</string>在 values-xlarge 文件夹中(strings.xml)

  • 在代码中:

    字符串 mType = getString(R.string.screentype);

    if (mType != null && mType.equals("LARGE") {

    // 从 4~7 英寸

    } else if (mType != null && mType.equals("XLARGE") {

    // 从 7~10 英寸

    }

于 2015-02-01T05:03:22.850 回答
1

瞧!这就是区分平板电脑和手机所需的全部内容

1.获取屏幕宽度的辅助函数:

private float getScreenWidth() {
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    return Math.min(metrics.widthPixels, metrics.heightPixels) / metrics.density;
}

2.判断设备是否为平板电脑的功能

boolean isTablet() {
    return getScreenWidth() >= 600;
}

3. 最后,如果您希望针对不同的设备尺寸执行不同的操作:

boolean is7InchTablet() {
    return getScreenWidth() >= 600 && getScreenWidth() < 720;
}

boolean is10InchTablet() {
    return getScreenWidth() >= 720;
}
于 2019-07-06T07:26:22.760 回答
0

这里有一些有用的 kotlin 扩展:

    
    fun DisplayMetrics.isTablet(): Boolean {
        return getScreenWidth() >= 600
    }
    
    fun DisplayMetrics.is7InchTablet(): Boolean {
        return getScreenWidth() >= 600 && getScreenWidth() < 720
    }
    
    fun DisplayMetrics.is10InchTablet(): Boolean {
        return getScreenWidth() >= 720
    }
    
    fun DisplayMetrics.getScreenWidth(): Float {
        return widthPixels.coerceAtMost(heightPixels) / density
    }

于 2020-04-14T07:51:57.153 回答