如何在Android中检查设备是Tablet,Mobile还是Android TV

Muh*_*dil 3 android

我正在制作一个在不同设备上表现不同的应用程序.有没有办法检查我的应用程序是否在电视设备,手机或平板电脑上运行?即使我想检查我在模拟器上运行我的应用程序.在一些链接中,我看到我们可以检查内部版本号或类似的东西.我只是想确定哪些是能让我们知道设备不同的主要内容?

Igo*_*sky 6

根据定义,平板电脑是7英寸或更高.这是一种检查它的方法:

/**
 * Checks if the device is a tablet (7" or greater).
 */
private boolean checkIsTablet() {
    Display display = ((Activity) this.mContext).getWindowManager().getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);

    float widthInches = metrics.widthPixels / metrics.xdpi;
    float heightInches = metrics.heightPixels / metrics.ydpi;
    double diagonalInches = Math.sqrt(Math.pow(widthInches, 2) + Math.pow(heightInches, 2));
    return diagonalInches >= 7.0;
}
Run Code Online (Sandbox Code Playgroud)

以下是如何检查设备是否为Android TV:

/**
 * Checks if the device is Android TV.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private boolean checkIsTelevision() {
    int uiMode = mContext.getResources().getConfiguration().uiMode;
    return (uiMode & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_TELEVISION;
}
Run Code Online (Sandbox Code Playgroud)

编辑:正如下面的Redshirt用户所指出的,上面的代码片段只会检测应用程序是否在MODE_TYPE_TELEVISION上运行.因此,要专门检测Android TV,您也可以使用此布尔检查: context.getPackageManager().hasSystemFeature("com.google.android.tv")

  • 如果您将适当的库添加到 build.gradle,Fire TV 可以显示 Leanback 活动,但它不使用 Leanback 启动器。上面的评论说它正在测试 Android TV,但这并不是该方法实际执行的操作。以下代码介绍了如何测试 Android TV。对于 Fire TV,它将返回 false,但对于实际的 Android TV 设备(例如 nvidiashield),它将返回 true。`getPackageManager().hasSystemFeature("android.software.leanback")` (2认同)