我想了解一种设备的信息,看看它是智能手机还是平板电脑。我该怎么做呢?

我想显示不同的网页资源基于设备的类型:

String s="Debug-infos:";
s += "\n OS Version: " + System.getProperty("os.version") + "(" +    android.os.Build.VERSION.INCREMENTAL + ")";
s += "\n OS API Level: " + android.os.Build.VERSION.SDK;
s += "\n Device: " + android.os.Build.DEVICE;
s += "\n Model (and Product): " + android.os.Build.MODEL + " ("+ android.os.Build.PRODUCT + ")";

然而,这似乎对我的情况毫无用处。


这个解决方案现在对我很有效:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;

if (SharedCode.width > 1023 || SharedCode.height > 1023){
   //code for big screen (like tablet)
}else{
   //code for small screen (like smartphone)
}

当前回答

由于平板电脑通常比智能手机大,而且低分辨率平板电脑的像素可能与高分辨率智能手机相同,解决这个问题的一种方法是计算设备的物理尺寸(而不是分辨率):

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

    float yInches= metrics.heightPixels/metrics.ydpi;
    float xInches= metrics.widthPixels/metrics.xdpi;

   if (yInches> smallestTabletSize|| xInches > smallestTabletSize)
    {
                  //We are on a 
    }

其他回答

由于平板电脑通常比智能手机大,而且低分辨率平板电脑的像素可能与高分辨率智能手机相同,解决这个问题的一种方法是计算设备的物理尺寸(而不是分辨率):

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

    float yInches= metrics.heightPixels/metrics.ydpi;
    float xInches= metrics.widthPixels/metrics.xdpi;

   if (yInches> smallestTabletSize|| xInches > smallestTabletSize)
    {
                  //We are on a 
    }

我使用的解决方案是定义两个布局。例如,将布局文件夹设置为 layout-sw600dp 我用它来为我的平板电脑用户提供一个菜单按钮,并为手机用户隐藏这个按钮。这样,我(还)不必为我现有的应用程序实现动作栏……

更多细节请看这篇文章。

我认为平板电脑至少要有6.5英寸的屏幕。这是如何计算它,基于诺尔夫的答案上面。

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

float yInches= metrics.heightPixels/metrics.ydpi;
float xInches= metrics.widthPixels/metrics.xdpi;
double diagonalInches = Math.sqrt(xInches*xInches + yInches*yInches);
if (diagonalInches>=6.5){
    // 6.5inch device or bigger
}else{
    // smaller device
}

回复:上面关于如何区分电话和非电话的正题:据我所知,只有电话有15位IMEI(国际移动站设备标识),所以下面的代码将明确区分电话和非电话:

    TelephonyManager manager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
    String deviceInfo = "";
    deviceInfo += manager.getDeviceId(); // the IMEI
    Log.d(TAG, "IMEI or unique ID is " + deviceInfo);

    if (manager.getDeviceId() == null) {
        Log.d(TAG, "This device is NOT a phone");
    } else {
        Log.d(TAG, "This device is a phone.");
    }

我发现在一个Nook模拟器getPhoneType()返回phoneType的“GSM”出于某种原因,所以它似乎检查手机类型是不可靠的。同样,对于处于飞行模式的手机,getNetworkType()将返回0。事实上,飞行模式也会导致getLine1Number()和getSim*方法返回null。但即使在飞行模式下,手机的IMEI仍然存在。

我在我所有的应用程序中都使用了这种方法,并且非常成功:

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