平板电脑或手机 - Android

发布于 2024-11-03 18:38:10 字数 58 浏览 1 评论 0原文

有没有办法检查用户是否使用平板电脑或手机? 我的倾斜功能和新平板电脑(Transformer)出现问题

Is there a way to check if the user is using a tablet or a phone?
I've got problems with my tilt function and my new tablet (Transformer)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

风和你 2024-11-10 18:38:10

正如前面所提到的,你不想检查设备是平板电脑还是手机,而是想了解设备的功能,

大多数时候,平板电脑和手机的区别在于屏幕size 这就是为什么你想使用不同的布局文件。这些文件存储在 res/layout- 目录中。您可以在 res/values- 目录中为每个布局创建一个 XML 文件,并将 int/bool/string 资源放入其中以区分您使用的布局。

示例:

文件 res/values/screen.xml(假设 res/layout/ 包含手机的布局文件)

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="screen_type">phone</string>
</resources>

文件 res/values-sw600dp/screen.xml(假设 res/layout-sw600dp/ 包含 Nexus 7 等小型平板电脑的布局文件)

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="screen_type">7-inch-tablet</string>
</resources>

文件 res/values-sw720dp/screen.xml(假设 res/layout-sw720dp/ 包含 Nexus 10 等大型平板电脑的布局文件)

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="screen_type">10-inch-tablet</string>
</resources>

: 屏幕类型可通过 R.string.screen_type 常量访问。

As it has been mentioned before, you do not want to check whether the device is a tablet or a phone but you want to know about the features of the device,

Most of the time, the difference between a tablet and a phone is the screen size which is why you want to use different layout files. These files are stored in the res/layout-<qualifiers> directories. You can create an XML file in the directoy res/values-<same qualifiers> for each of your layouts and put an int/bool/string resource into it to distinguish between the layouts you use.

Example:

File res/values/screen.xml (assuming res/layout/ contains your layout files for handsets)

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="screen_type">phone</string>
</resources>

File res/values-sw600dp/screen.xml (assuming res/layout-sw600dp/ contains your layout files for small tablets like the Nexus 7)

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="screen_type">7-inch-tablet</string>
</resources>

File res/values-sw720dp/screen.xml (assuming res/layout-sw720dp/ contains your layout files for large tablets like the Nexus 10):

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="screen_type">10-inch-tablet</string>
</resources>

Now the screen type is accessible via the R.string.screen_type constant.

送君千里 2024-11-10 18:38:10

要检测设备是否是平板电脑,请使用以下代码:

public boolean isTablet(Context context) {
    boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);
    boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
    return (xlarge || large);
}

LARGE 和 XLARGE 屏幕尺寸由制造商根据使用时距眼睛的距离确定(因此是平板电脑的概念)。

详细信息:http://groups.google.com/group/android-开发人员/browse_thread/thread/d6323d81f226f93f

To detect whether or not the device is a tablet use the following code:

public boolean isTablet(Context context) {
    boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);
    boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
    return (xlarge || large);
}

LARGE and XLARGE Screen Sizes are determined by the manufacturer based on the distance from the eye they are to be used at (thus the idea of a tablet).

More info : http://groups.google.com/group/android-developers/browse_thread/thread/d6323d81f226f93f

半山落雨半山空 2024-11-10 18:38:10

这篇文章对我帮助很大,

不幸的是我没有必要的声誉来评估所有对我有帮助的答案。

我需要确定我的设备是平板电脑还是手机,这样我就能够实现屏幕的逻辑。根据我的分析,从 MDPI 开始,平板电脑的尺寸必须超过 7 英寸(超大)。

下面是根据这篇文章创建的代码。

/**
 * Checks if the device is a tablet or a phone
 * 
 * @param activityContext
 *            The Activity Context.
 * @return Returns true if the device is a Tablet
 */
public static boolean isTabletDevice(Context activityContext) {
    // Verifies if the Generalized Size of the device is XLARGE to be
    // considered a Tablet
    boolean xlarge = ((activityContext.getResources().getConfiguration().screenLayout & 
                        Configuration.SCREENLAYOUT_SIZE_MASK) == 
                        Configuration.SCREENLAYOUT_SIZE_XLARGE);

    // If XLarge, checks if the Generalized Density is at least MDPI
    // (160dpi)
    if (xlarge) {
        DisplayMetrics metrics = new DisplayMetrics();
        Activity activity = (Activity) activityContext;
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

        // MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
        // DENSITY_TV=213, DENSITY_XHIGH=320
        if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
                || metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
                || metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
                || metrics.densityDpi == DisplayMetrics.DENSITY_TV
                || metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {

            // Yes, this is a tablet!
            return true;
        }
    }

    // No, this is not a tablet!
    return false;
}

This post helped me a lot,

Unfortunately I don't have the reputation necessary to evaluate all the answers that helped me.

I needed to identify if my device was a tablet or a phone, with that I would be able to implement the logic of the screen. And in my analysis the tablet must be more than 7 inches (Xlarge) starting at MDPI.

Here's the code below, which was created based on this post.

/**
 * Checks if the device is a tablet or a phone
 * 
 * @param activityContext
 *            The Activity Context.
 * @return Returns true if the device is a Tablet
 */
public static boolean isTabletDevice(Context activityContext) {
    // Verifies if the Generalized Size of the device is XLARGE to be
    // considered a Tablet
    boolean xlarge = ((activityContext.getResources().getConfiguration().screenLayout & 
                        Configuration.SCREENLAYOUT_SIZE_MASK) == 
                        Configuration.SCREENLAYOUT_SIZE_XLARGE);

    // If XLarge, checks if the Generalized Density is at least MDPI
    // (160dpi)
    if (xlarge) {
        DisplayMetrics metrics = new DisplayMetrics();
        Activity activity = (Activity) activityContext;
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

        // MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
        // DENSITY_TV=213, DENSITY_XHIGH=320
        if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
                || metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
                || metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
                || metrics.densityDpi == DisplayMetrics.DENSITY_TV
                || metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {

            // Yes, this is a tablet!
            return true;
        }
    }

    // No, this is not a tablet!
    return false;
}
青衫负雪 2024-11-10 18:38:10

为什么不计算屏幕对角线的大小并用它来决定该设备是手机还是平板电脑?

private boolean isTablet()
{
    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    display.getMetrics(displayMetrics);

    int width = displayMetrics.widthPixels / displayMetrics.densityDpi;
    int height = displayMetrics.heightPixels / displayMetrics.densityDpi;

    double screenDiagonal = Math.sqrt( width * width + height * height );
    return (screenDiagonal >= 9.0 );
}

当然,人们可能会争论阈值是否应该为 9 英寸或更小。

Why not calculate the size of the screen diagonal and use that to make the decision whether the device is a phone or tablet?

private boolean isTablet()
{
    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    display.getMetrics(displayMetrics);

    int width = displayMetrics.widthPixels / displayMetrics.densityDpi;
    int height = displayMetrics.heightPixels / displayMetrics.densityDpi;

    double screenDiagonal = Math.sqrt( width * width + height * height );
    return (screenDiagonal >= 9.0 );
}

Of course one can argue whether the threshold should be 9 inches or less.

や莫失莫忘 2024-11-10 18:38:10

没有什么区别。您应该定义您认为的差异并进行检查。 Galaxy Tab 是手机吗?或者平板电脑?为什么?

您应该定义您正在寻找哪些特定功能,并为其编写代码。

看来您正在寻找“倾斜”。我认为这与加速度计相同(这是一个词吗?)。您可以使用以下命令检查设备是否支持它:(

public class Accel extends Activity implements SensorListener {
...
  SensorManager sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
  boolean accelSupported = sensorMgr.registerListener(this,
        SENSOR_ACCELEROMETER,
        SENSOR_DELAY_UI);
...
}

来自 http:// stuffthathappens.com/blog/2009/03/15/android-accelerometer/ 我没有测试过)

there is no difference. You should define what you think is the difference, and check for that. Is a galaxy tab a phone? or a tablet? and why?

You should define what specific features you are looking for, and code for that.

It seems you are looking for 'tilt'. I think this is the same as the accelerometer (is that a word?). You can just check if the device supports it, using:

public class Accel extends Activity implements SensorListener {
...
  SensorManager sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
  boolean accelSupported = sensorMgr.registerListener(this,
        SENSOR_ACCELEROMETER,
        SENSOR_DELAY_UI);
...
}

(from http://stuffthathappens.com/blog/2009/03/15/android-accelerometer/ . i have not tested it)

和我恋爱吧 2024-11-10 18:38:10

我的假设是,当您定义“手机/电话”时,您希望知道是否可以在设备上拨打电话,而这在定义为“平板电脑”的设备上无法完成。验证这一点的方法如下。如果您想了解基于传感器、屏幕尺寸等的信息,那么这确实是一个不同的问题。

此外,虽然使用屏幕分辨率或资源管理大与超大,可能是过去新的“移动”设备的有效方法,但现在配备了如此大的屏幕和高分辨率,以至于它们模糊了这条界限,而如果您真的愿意的话要了解电话呼叫与没有电话呼叫功能,以下是“最佳”。

TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
if(manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE){
    return "Tablet";
}else{
    return "Mobile";
}

My assumption is that when you define 'Mobile/Phone' you wish to know whether you can make a phone call on the device which cannot be done on something that would be defined as a 'Tablet'. The way to verify this is below. If you wish to know something based on sensors, screen size, etc then this is really a different question.

Also, while using screen resolution, or the resource managements large vs xlarge, may have been a valid approach in the past new 'Mobile' devices are now coming with such large screens and high resolutions that they are blurring this line while if you really wish to know phone call vs no phone call capability the below is 'best'.

TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
if(manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE){
    return "Tablet";
}else{
    return "Mobile";
}
单身情人 2024-11-10 18:38:10

在 Google IOSched 2017 应用程序中 源码,使用的方法如下:

public static boolean isTablet(Context context) {
    return context.getResources().getConfiguration().smallestScreenWidthDp >= 600;
}

In the Google IOSched 2017 app source code, the following method is used:

public static boolean isTablet(Context context) {
    return context.getResources().getConfiguration().smallestScreenWidthDp >= 600;
}
睡美人的小仙女 2024-11-10 18:38:10

基于 Robert Dale Johnson III 和 Helton Isac 我想出了这段代码希望这很有用

public static boolean isTablet(Context context) {
    TelephonyManager manager = 
        (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
    if (manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {
        //Tablet
        return true;
    } else {
        //Mobile
        return false; 
    }
}

public static boolean isTabletDevice(Context activityContext) {
    // Verifies if the Generalized Size of the device is XLARGE to be
    // considered a Tablet
    boolean xlarge = 
         ((activityContext.getResources().getConfiguration().screenLayout & 
           Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);

    // If XLarge, checks if the Generalized Density is at least MDPI (160dpi)
    if (xlarge) {
        DisplayMetrics metrics = new DisplayMetrics();
        Activity activity = (Activity) activityContext;
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

        // MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
        // DENSITY_TV=213, DENSITY_XHIGH=320
        if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
                  || metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
                  || metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM   
                  || metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {

             // Yes, this is a tablet!
             return true;
        }
    }

    // No, this is not a tablet!
    return false;
}

所以在你的代码中做一个过滤器

if(isTabletDevice(Utilities.this) && isTablet(Utilities.this)){
    //Tablet
} else {
    //Phone
}

Based on Robert Dale Johnson III and Helton Isac I came up with this code Hope this is useful

public static boolean isTablet(Context context) {
    TelephonyManager manager = 
        (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
    if (manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {
        //Tablet
        return true;
    } else {
        //Mobile
        return false; 
    }
}

public static boolean isTabletDevice(Context activityContext) {
    // Verifies if the Generalized Size of the device is XLARGE to be
    // considered a Tablet
    boolean xlarge = 
         ((activityContext.getResources().getConfiguration().screenLayout & 
           Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);

    // If XLarge, checks if the Generalized Density is at least MDPI (160dpi)
    if (xlarge) {
        DisplayMetrics metrics = new DisplayMetrics();
        Activity activity = (Activity) activityContext;
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

        // MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
        // DENSITY_TV=213, DENSITY_XHIGH=320
        if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
                  || metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
                  || metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM   
                  || metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {

             // Yes, this is a tablet!
             return true;
        }
    }

    // No, this is not a tablet!
    return false;
}

So in your code make a filter like

if(isTabletDevice(Utilities.this) && isTablet(Utilities.this)){
    //Tablet
} else {
    //Phone
}
冰雪之触 2024-11-10 18:38:10

不需要代码

其他答案列出了以编程方式确定设备是手机还是平板电脑的多种方法。但是,如果您阅读文档,这不是推荐的方式支持各种屏幕尺寸。

相反,为平板电脑或手机声明不同的资源。您可以通过为 layoutvalues 等添加其他资源文件夹来执行此操作。

  • 对于 Android 3.2(API 级别 13),添加 sw600dp 文件夹。这意味着最小宽度至少为 600dp,大约是手机/平板电脑的差距。但是,您也可以添加其他尺寸。查看此答案,了解如何添加其他布局资源文件的示例。


  • 如果您还支持 Android 3.2 之前的设备,则需要添加 largexlarge 文件夹以支持平板电脑。 (手机通常普通。)

下面是一张图片,显示了在为不同的屏幕尺寸添加额外的 xml 文件后您的资源可能会是什么样子。

输入图片此处描述

使用此方法时,系统会为您确定一切。您不必担心运行时正在使用哪个设备。您只需提供适当的资源,然后让 Android 完成所有工作。

注释

  • 您可以使用别名来避免复制相同的资源文件。

值得一读的 Android 文档

No code needed

The other answers list many ways of programmatically determining whether the device is a phone or tablet. However, if you read the documentation, that is not the recommended way to support various screen sizes.

Instead, declare different resources for tablets or phones. You do this my adding additional resource folders for layout, values, etc.

  • For Android 3.2 (API level 13) on, add a sw600dp folder. This means the smallest width is at least 600dp, which is approximately the phone/tablet divide. However, you can also add other sizes as well. Check out this answer for an example of how to add an additional layout resource file.

  • If you are also supporting pre Android 3.2 devices, then you will need to add large or xlarge folders to support tablets. (Phones are generally small and normal.)

Here is an image of what your resources might like after adding an extra xml files for different screen sizes.

enter image description here

When using this method, the system determines everything for you. You don't have to worry about which device is being used at run time. You just provide the appropriate resources and let Android do all the work.

Notes

  • You can use aliases to avoid duplicating identical resource files.

Android docs worth reading

‖放下 2024-11-10 18:38:10

对于那些想参考Google决定哪些设备将使用平板电脑UI的代码可以参考以下内容:

  // SystemUI (status bar) layout policy
        int shortSizeDp = shortSize
                * DisplayMetrics.DENSITY_DEFAULT
                / DisplayMetrics.DENSITY_DEVICE;

        if (shortSizeDp < 600) {
            // 0-599dp: "phone" UI with a separate status & navigation bar
            mHasSystemNavBar = false;
            mNavigationBarCanMove = true;
        } else if (shortSizeDp < 720) {
            // 600-719dp: "phone" UI with modifications for larger screens
            mHasSystemNavBar = false;
            mNavigationBarCanMove = false;
        } else {
            // 720dp: "tablet" UI with a single combined status & navigation bar
            mHasSystemNavBar = true;
            mNavigationBarCanMove = false;
        }
        }

For those who want to refer to Google's code of deciding which devices will use a Tablet UI can refer to below:

  // SystemUI (status bar) layout policy
        int shortSizeDp = shortSize
                * DisplayMetrics.DENSITY_DEFAULT
                / DisplayMetrics.DENSITY_DEVICE;

        if (shortSizeDp < 600) {
            // 0-599dp: "phone" UI with a separate status & navigation bar
            mHasSystemNavBar = false;
            mNavigationBarCanMove = true;
        } else if (shortSizeDp < 720) {
            // 600-719dp: "phone" UI with modifications for larger screens
            mHasSystemNavBar = false;
            mNavigationBarCanMove = false;
        } else {
            // 720dp: "tablet" UI with a single combined status & navigation bar
            mHasSystemNavBar = true;
            mNavigationBarCanMove = false;
        }
        }
各自安好 2024-11-10 18:38:10

这个方法是Google推荐的。我在 Google 官方 Android 应用 iosched 中看到此代码

public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}

This method is a recommend by Google. I see this code in Google Offical Android App iosched

public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
遗忘曾经 2024-11-10 18:38:10

如果屏幕尺寸检测在较新的设备上未返回正确的值,请尝试:

/*
 Returns '1' if device is a tablet
 or '0' if device is not a tablet.
 Returns '-1' if an error occured.
 May require READ_EXTERNAL_STORAGE
 permission.
 */
public static int isTablet()
{
    try
    {
        InputStream ism = Runtime.getRuntime().exec("getprop ro.build.characteristics").getInputStream();
        byte[] bts = new byte[1024];
        ism.read(bts);
        ism.close();

        boolean isTablet = new String(bts).toLowerCase().contains("tablet");
        return isTablet ? 1 : 0;
    }
    catch (Throwable t)
    {t.printStackTrace(); return -1;}
}

在 Android 4.2.2 上测试(抱歉我的英语不好。)

If screen size detection doesn't return correct value on newer devices, give a try:

/*
 Returns '1' if device is a tablet
 or '0' if device is not a tablet.
 Returns '-1' if an error occured.
 May require READ_EXTERNAL_STORAGE
 permission.
 */
public static int isTablet()
{
    try
    {
        InputStream ism = Runtime.getRuntime().exec("getprop ro.build.characteristics").getInputStream();
        byte[] bts = new byte[1024];
        ism.read(bts);
        ism.close();

        boolean isTablet = new String(bts).toLowerCase().contains("tablet");
        return isTablet ? 1 : 0;
    }
    catch (Throwable t)
    {t.printStackTrace(); return -1;}
}

Tested on Android 4.2.2 (sorry for my English.)

风向决定发型 2024-11-10 18:38:10

如果您的目标只是 API 级别 >= 13,那么请尝试

public static boolean isTablet(Context context) {
    return context.getResources().getConfiguration().smallestScreenWidthDp >= 600;
}

欢呼:-)

If you are only targeting API level >= 13 then try

public static boolean isTablet(Context context) {
    return context.getResources().getConfiguration().smallestScreenWidthDp >= 600;
}

cheers :-)

捶死心动 2024-11-10 18:38:10

考虑到“新”接受的目录(例如 value-sw600dp),我根据屏幕宽度 DP 创建了此方法:

 public static final int TABLET_MIN_DP_WEIGHT = 450;
 protected static boolean isSmartphoneOrTablet(Activity act){
    DisplayMetrics metrics = new DisplayMetrics();
    act.getWindowManager().getDefaultDisplay().getMetrics(metrics);

    int dpi = 0;
    if (metrics.widthPixels < metrics.heightPixels){
        dpi = (int) (metrics.widthPixels / metrics.density);
    }
    else{
        dpi = (int) (metrics.heightPixels / metrics.density);
    }

    if (dpi < TABLET_MIN_DP_WEIGHT)         return true;
    else                                    return false;
}

在此列表中,您可以找到一些流行设备和平板电脑尺寸的 DP:

Wdp / Hdp

GALAXY Nexus : 360 / 567
XOOM:1280 / 752
银河笔记:400 / 615
Nexus 7:961 / 528
银河选项卡 (>7 &<10):1280 / 752
GALAXY S3:360 / 615

Wdp = 宽度 dp
Hdp = 高度 dp

Thinking on the "new" acepted directories (values-sw600dp for example) i created this method based on the screen' width DP:

 public static final int TABLET_MIN_DP_WEIGHT = 450;
 protected static boolean isSmartphoneOrTablet(Activity act){
    DisplayMetrics metrics = new DisplayMetrics();
    act.getWindowManager().getDefaultDisplay().getMetrics(metrics);

    int dpi = 0;
    if (metrics.widthPixels < metrics.heightPixels){
        dpi = (int) (metrics.widthPixels / metrics.density);
    }
    else{
        dpi = (int) (metrics.heightPixels / metrics.density);
    }

    if (dpi < TABLET_MIN_DP_WEIGHT)         return true;
    else                                    return false;
}

And on this list you can find some of the DP of popular devices and tablet sizes:

Wdp / Hdp

GALAXY Nexus: 360 / 567
XOOM: 1280 / 752
GALAXY NOTE: 400 / 615
NEXUS 7: 961 / 528
GALAXY TAB (>7 && <10): 1280 / 752
GALAXY S3: 360 / 615

Wdp = Width dp
Hdp = Height dp

花桑 2024-11-10 18:38:10

好吧,对我有用的最佳解决方案非常简单:

private boolean isTabletDevice(Resources resources) {   
    int screenLayout = resources.getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
    boolean isScreenLarge = (screenLayout == Configuration.SCREENLAYOUT_SIZE_LARGE);
    boolean isScreenXlarge = (screenLayout == Configuration.SCREENLAYOUT_SIZE_XLARGE);
    return (isScreenLarge || isScreenXlarge);
}

像这样使用:

public void onCreate(Bundle savedInstanceState) {
    [...]
    if (this.isTabletDevice(this.getResources()) == true) {
        [...]
    }
}

我真的不想查看像素大小,而只想依赖屏幕大小。

Nexus 7 (LARGE) 被检测为平板电脑,但 Galaxy S3 (NORMAL) 则无法正常工作。

Well, the best solution that worked for me is quite simple:

private boolean isTabletDevice(Resources resources) {   
    int screenLayout = resources.getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
    boolean isScreenLarge = (screenLayout == Configuration.SCREENLAYOUT_SIZE_LARGE);
    boolean isScreenXlarge = (screenLayout == Configuration.SCREENLAYOUT_SIZE_XLARGE);
    return (isScreenLarge || isScreenXlarge);
}

Used like this:

public void onCreate(Bundle savedInstanceState) {
    [...]
    if (this.isTabletDevice(this.getResources()) == true) {
        [...]
    }
}

I really don't want to look at the pixels sizes but only rely on the screen size.

Works well as Nexus 7 (LARGE) is detected as a tablet, but not Galaxy S3 (NORMAL).

贪恋 2024-11-10 18:38:10

当设备是平板电脑时,使用此方法会返回 true

public boolean isTablet(Context context) {  
    return (context.getResources().getConfiguration().screenLayout   
        & Configuration.SCREENLAYOUT_SIZE_MASK)    
        >= Configuration.SCREENLAYOUT_SIZE_LARGE; 
}

Use this method which returns true when the device is a tablet

public boolean isTablet(Context context) {  
    return (context.getResources().getConfiguration().screenLayout   
        & Configuration.SCREENLAYOUT_SIZE_MASK)    
        >= Configuration.SCREENLAYOUT_SIZE_LARGE; 
}
我不咬妳我踢妳 2024-11-10 18:38:10

我知道这不是您问题的直接答案,但这里的其他答案很好地说明了如何识别屏幕尺寸。您在问题中写道,您遇到了倾斜问题,这也发生在我身上。

如果您在智能手机上运行陀螺仪(或旋转传感器),则根据该设备的默认方向,x 轴和 y 轴的定义可能与平板电脑上不同(例如,三星 GS2 是默认纵向,三星 GT-7310 是默认纵向)默认横向,新的 Google Nexus 7 默认纵向,尽管它是平板电脑!)。

现在,如果您想使用陀螺仪,您最终可能会得到一个适用于智能手机的可行解决方案,但在某些平板电脑上会出现轴混乱,反之亦然。

如果您使用上面的解决方案之一仅选择屏幕尺寸,然后应用

SensorManager.remapCoordinateSystem(inputRotationMatrix, SensorManager.AXIS_X, 
    SensorManager.AXIS_Y, outputRotationMatrix);

翻转轴(如果它具有大或超大屏幕尺寸),这可能适用于 90% 的情况,但例如在 Nexus 7 上会造成麻烦(因为它有默认的纵向方向和大屏幕尺寸)。

解决此问题的最简单方法是在 API 演示附带的 RotationVectorSample 中提供,方法是在清单中将 sceenOrientation 设置为 nosensor

<activity
    ...
    android:screenOrientation="nosensor">
...
</activity>

I know this is not directly an answer to your question, but other answers here give a good idea of how to identify screen size. You wrote in your question that you got problems with the tilting and this just happened to me as well.

If you run the gyroscope (or rotation sensor) on a smartphone the x- and y-axis can be differently defined than on a tablet, according to the default orientation of that device (e.g. Samsung GS2 is default portrait, Samsung GT-7310 is default landscape, new Google Nexus 7 is default portrait, although it is a tablet!).

Now if you want to use Gyroscope you might end up with a working solution for smartphones, but axis-confusion on some tablets or the other way round.

If you use one of the solutions from above to only go for screen-size and then apply

SensorManager.remapCoordinateSystem(inputRotationMatrix, SensorManager.AXIS_X, 
    SensorManager.AXIS_Y, outputRotationMatrix);

to flip the axis if it has a large or xlarge screen-size this might work in 90% of the cases but for example on the Nexus 7 it will cause troubles (because it has default portrait orientation and a large screen-size).

The simplest way to fix this is provided in the RotationVectorSample that ships with the API demos by setting the sceenOrientation to nosensor in your manifest:

<activity
    ...
    android:screenOrientation="nosensor">
...
</activity>
你不是我要的菜∠ 2024-11-10 18:38:10

包管理器中的 com.sec.feature.multiwindow.tablet 仅特定于平板电脑,而 com.sec.feature.multiwindow.phone 特定于手机。

com.sec.feature.multiwindow.tablet in package manager is specific only to tablet and com.sec.feature.multiwindow.phone is specific to phone.

七色彩虹 2024-11-10 18:38:10

下面的方法是计算设备屏幕的对角线长度来确定设备是手机还是平板电脑。此方法唯一关心的是决定设备是否为平板电脑的阈值是多少。在下面的示例中,我将其设置为 7 英寸及以上。

public static boolean isTablet(Activity act)
{
    Display display = act.getWindow().getWindowManager().getDefaultDisplay();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    display.getMetrics(displayMetrics);

    float width = displayMetrics.widthPixels / displayMetrics.xdpi;
    float height = displayMetrics.heightPixels / displayMetrics.ydpi;

    double screenDiagonal = Math.sqrt( width * width + height * height );
    int inch = (int) (screenDiagonal + 0.5);
    Toast.makeText(act, "inch : "+ inch, Toast.LENGTH_LONG).show();
    return (inch >= 7 );
}

below method is calculating the device screen's diagonal length to decide the device is a phone or tablet. the only concern for this method is what is the threshold value to decide weather the device is tablet or not. in below example i set it as 7 inch and above.

public static boolean isTablet(Activity act)
{
    Display display = act.getWindow().getWindowManager().getDefaultDisplay();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    display.getMetrics(displayMetrics);

    float width = displayMetrics.widthPixels / displayMetrics.xdpi;
    float height = displayMetrics.heightPixels / displayMetrics.ydpi;

    double screenDiagonal = Math.sqrt( width * width + height * height );
    int inch = (int) (screenDiagonal + 0.5);
    Toast.makeText(act, "inch : "+ inch, Toast.LENGTH_LONG).show();
    return (inch >= 7 );
}
痴情 2024-11-10 18:38:10
public boolean isTablet() {
        int screenLayout = getResources().getConfiguration().screenLayout;
        return (Build.VERSION.SDK_INT >= 11 &&
                (((screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) || 
                 ((screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE)));
    }
public boolean isTablet() {
        int screenLayout = getResources().getConfiguration().screenLayout;
        return (Build.VERSION.SDK_INT >= 11 &&
                (((screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) || 
                 ((screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE)));
    }
余厌 2024-11-10 18:38:10

区分手机和平板电脑变得越来越困难。例如(截至 2015 年 8 月)Samsung Mega 6.3 设备从 sw600dp 提取资源文件夹——就 Android 而言,它是一台平板电脑。

@Vyshnavi 的答案适用于我们测试过的所有设备,但不适用于 Mega 6.3。

@Helton Isac 上面的答案将 Mega 6.3 作为手机返回 - 但由于该设备仍然从 sw600dp 获取资源,因此可能会导致其他问题 - 例如,如果您在手机上使用 viewpager 而不是在平板电脑上使用,您最终会遇到 NPE 错误。

最后,似乎有太多的条件需要检查,我们可能不得不接受有些手机实际上是平板电脑:-P

It is getting increasingly harder to draw the line between phone and tablet. For instance (as of Aug 2015) the Samsung Mega 6.3 device pulls resources from the sw600dp folders -- so as far as Android is concerned it is a tablet.

The answer from @Vyshnavi works in all devices we have tested but not for Mega 6.3.

@Helton Isac answer above returns the Mega 6.3 as a phone -- but since the device still grabs resources from sw600dp it can cause other issues - for instance if you use a viewpager for phones and not for tablets you'll wind up with NPE errors.

In the end it just seems that there are too many conditions to check for and we may just have to accept that some phones are actually tablets :-P

南街九尾狐 2024-11-10 18:38:10

这是我使用的方法:

public static boolean isTablet(Context ctx){    
    return = (ctx.getResources().getConfiguration().screenLayout 
    & Configuration.SCREENLAYOUT_SIZE_MASK) 
    >= Configuration.SCREENLAYOUT_SIZE_LARGE; 
}

使用:

Configuration。SCREENLAYOUT_SIZE_MASK

配置。SCREENLAYOUT_SIZE_LARGE

这是推荐的方法!

This is the method that i use :

public static boolean isTablet(Context ctx){    
    return = (ctx.getResources().getConfiguration().screenLayout 
    & Configuration.SCREENLAYOUT_SIZE_MASK) 
    >= Configuration.SCREENLAYOUT_SIZE_LARGE; 
}

Using:

Configuration.SCREENLAYOUT_SIZE_MASK

Configuration.SCREENLAYOUT_SIZE_LARGE

This is the recommended method!

〃温暖了心ぐ 2024-11-10 18:38:10

为什么用这个?

Use this method which returns true when the device is a tablet

public boolean isTablet(Context context) {  
return (context.getResources().getConfiguration().screenLayout   
    & Configuration.SCREENLAYOUT_SIZE_MASK)    
    >= Configuration.SCREENLAYOUT_SIZE_LARGE; 
}

我在上面看到了很多方法。配置类在下面得到了正确的答案:

    /**
 * Check if the Configuration's current {@link #screenLayout} is at
 * least the given size.
 *
 * @param size The desired size, either {@link #SCREENLAYOUT_SIZE_SMALL},
 * {@link #SCREENLAYOUT_SIZE_NORMAL}, {@link #SCREENLAYOUT_SIZE_LARGE}, or
 * {@link #SCREENLAYOUT_SIZE_XLARGE}.
 * @return Returns true if the current screen layout size is at least
 * the given size.
 */
public boolean isLayoutSizeAtLeast(int size) {
    int cur = screenLayout&SCREENLAYOUT_SIZE_MASK;
    if (cur == SCREENLAYOUT_SIZE_UNDEFINED) return false;
    return cur >= size;
}

只需调用:

 getResources().getConfiguration().
 isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_LARGE);

可以吗?

why use this?

Use this method which returns true when the device is a tablet

public boolean isTablet(Context context) {  
return (context.getResources().getConfiguration().screenLayout   
    & Configuration.SCREENLAYOUT_SIZE_MASK)    
    >= Configuration.SCREENLAYOUT_SIZE_LARGE; 
}

i see many ways above.the Configuration class has get the right answer just below:

    /**
 * Check if the Configuration's current {@link #screenLayout} is at
 * least the given size.
 *
 * @param size The desired size, either {@link #SCREENLAYOUT_SIZE_SMALL},
 * {@link #SCREENLAYOUT_SIZE_NORMAL}, {@link #SCREENLAYOUT_SIZE_LARGE}, or
 * {@link #SCREENLAYOUT_SIZE_XLARGE}.
 * @return Returns true if the current screen layout size is at least
 * the given size.
 */
public boolean isLayoutSizeAtLeast(int size) {
    int cur = screenLayout&SCREENLAYOUT_SIZE_MASK;
    if (cur == SCREENLAYOUT_SIZE_UNDEFINED) return false;
    return cur >= size;
}

just call :

 getResources().getConfiguration().
 isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_LARGE);

it's ok?

旧时浪漫 2024-11-10 18:38:10

我只需要在布局文件中检测智能手机/平板电脑,因为我正在使用导航代码。

我首先做的是创建一个layout-sw600dp目录,但效果不佳,因为它会在我的诺基亚8上以横向模式激活,但屏幕高度太小。

所以,我将目录重命名为layout-sw600dp-h400dp,然后就得到了想要的效果。 h-xxxdp 参数应取决于您想要在布局上放置的内容量,因此应取决于应用程序。

I needed to detect the smartphone/tablet only in the layout file, because I'm using the navigation code.

What I did first was to create a layout-sw600dp directory but it was not working well because it would activate on my Nokia 8 in landscape mode, but the screen height would be too small.

So, I renamed the directory as layout-sw600dp-h400dp and then I got the desired effect. The h-xxxdp parameter should depend on how much content you want to drop on your layout and as such should be application dependent.

梦魇绽荼蘼 2024-11-10 18:38:10

请查看下面的代码。

private boolean isTabletDevice() {
  if (android.os.Build.VERSION.SDK_INT >= 11) { // honeycomb
    // test screen size, use reflection because isLayoutSizeAtLeast is
    // only available since 11
    Configuration con = getResources().getConfiguration();
    try {
      Method mIsLayoutSizeAtLeast = con.getClass().getMethod(
      "isLayoutSizeAtLeast", int.class);
      boolean r = (Boolean) mIsLayoutSizeAtLeast.invoke(con,
      0x00000004); // Configuration.SCREENLAYOUT_SIZE_XLARGE
      return r;
    } catch (Exception x) {
      x.printStackTrace();
      return false;
    }
  }
  return false;
}

Please check out below code.

private boolean isTabletDevice() {
  if (android.os.Build.VERSION.SDK_INT >= 11) { // honeycomb
    // test screen size, use reflection because isLayoutSizeAtLeast is
    // only available since 11
    Configuration con = getResources().getConfiguration();
    try {
      Method mIsLayoutSizeAtLeast = con.getClass().getMethod(
      "isLayoutSizeAtLeast", int.class);
      boolean r = (Boolean) mIsLayoutSizeAtLeast.invoke(con,
      0x00000004); // Configuration.SCREENLAYOUT_SIZE_XLARGE
      return r;
    } catch (Exception x) {
      x.printStackTrace();
      return false;
    }
  }
  return false;
}
野却迷人 2024-11-10 18:38:10

我认为平板电脑的宽度和高度的最小和最大 600 像素,
所以需要知道屏幕密度和以 dp 为单位的高度/宽度,
检索值:

DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth(); 
int height = display.getHeight(); 
float density = metrics.density;  
if((width/density>=600 && height/density>=600))
 isTablette = true;
else
 isTablette = false;

I think a tablet has a min and max 600 px width and height,
so need to know the screen density and the height/width in dp,
to retrieve the value :

DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth(); 
int height = display.getHeight(); 
float density = metrics.density;  
if((width/density>=600 && height/density>=600))
 isTablette = true;
else
 isTablette = false;

南…巷孤猫 2024-11-10 18:38:10

例如,手机和平板电脑之间有一个重要的区别(至少对于我的程序而言)。这是设备的默认方向。手机为纵向,平板电脑为横向。以及分别确定设备的方法:

private static boolean isLandscapeDefault(Display display) {
    Log.d(TAG, "isTablet()");
    final int width = display.getWidth();
    final int height = display.getHeight();

    switch (display.getOrientation()) {
    case 0: case 2:
        if(width > height) return true;
        break;
    case 1: case 3:
        if(width < height) return true;
        break;
    }
    return false;
}

编辑:
与 Dan Hulme 讨论后更改了该方法的名称。

E.g. have one important difference (at least for my program) between the phone and tablet. It is the default orientation of the device. Phone has a portrait orientation, the tablet - landscape. And respectively method to determine the device:

private static boolean isLandscapeDefault(Display display) {
    Log.d(TAG, "isTablet()");
    final int width = display.getWidth();
    final int height = display.getHeight();

    switch (display.getOrientation()) {
    case 0: case 2:
        if(width > height) return true;
        break;
    case 1: case 3:
        if(width < height) return true;
        break;
    }
    return false;
}

EDITED:
Following the discussions with Dan Hulme changed the name of the method.

荒岛晴空 2024-11-10 18:38:10

我推荐 android 库“caffeine”,它包含手机或平板电脑,以及 10 英寸~!

非常容易使用。

图书馆在这里。

https://github.com/ShakeJ/Android-Caffeine-library

并使用

DisplayUtil.isTablet(this);
DisplayUtil.isTenInch(this);

I'm recommend android library 'caffeine' That's contain get Phone or tablet, and 10inch~!

very easy use.

the library is here.

https://github.com/ShakeJ/Android-Caffeine-library

and use

DisplayUtil.isTablet(this);
DisplayUtil.isTenInch(this);
黑寡妇 2024-11-10 18:38:10

对我来说,手机和平板电脑之间的区别不是设备的尺寸和/或像素密度,这会随着技术和品味而变化,而是屏幕比例。如果我要显示文本屏幕,我需要知道是否需要 15 行长行(手机)和 20 行短行(平板电脑)。对于我的游戏,我使用以下内容对我的软件将处理的矩形进行大致估计:

    Rect surfaceRect = getHolder().getSurfaceFrame();
    screenWidth = surfaceRect.width();
    screenHeight = surfaceRect.height();
    screenWidthF = (float) screenWidth;
    screenHeightF = (float) screenHeight;
    widthheightratio = screenWidthF/screenHeightF;
    if(widthheightratio>=1.5) {
        isTablet=false;
    }else {
        isTablet=true;
    }

For me the distinction between phone and tablet is not size of device and/or pixel density, which will change with technology and taste, but rather the screen ratio. If I'm displaying a screen of text I need to know if, say, 15 long lines are needed (phone) vs 20 shorter lines (tablet). For my game I use the following for a ballpark estimation of the rectangle my software will be dealing with:

    Rect surfaceRect = getHolder().getSurfaceFrame();
    screenWidth = surfaceRect.width();
    screenHeight = surfaceRect.height();
    screenWidthF = (float) screenWidth;
    screenHeightF = (float) screenHeight;
    widthheightratio = screenWidthF/screenHeightF;
    if(widthheightratio>=1.5) {
        isTablet=false;
    }else {
        isTablet=true;
    }
清风挽心 2024-11-10 18:38:10

我认为这是最简单的诚实方式。这将检查正在使用的屏幕尺寸:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();
int height = display.getHeight();

祝你好运!

I think this is the easiest way to be honest. This will check the screen size that's being used:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();
int height = display.getHeight();

Best of luck!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文