Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the device is Tablet, Mobile or Android TV in android

Tags:

android

I am making an application which will behave differently on different devices. Is there any way to check that my application is running on TV Device, Mobile or Tablet? Even I want to check I am running my application on Emulator. In some links I have seen we can check build number or things like these. I just want to make sure which is the main thing which can let us know that devices are different?

like image 581
Muhammad Adil Avatar asked Dec 19 '22 08:12

Muhammad Adil


2 Answers

By definition, a tablet is 7" or greater. Here is a method to check for it:

/**
 * 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;
}

And here is how to check whether the device is 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;
}

Edit: As pointed out by Redshirt user below, the above code snippet will only detect whether the app is running on a MODE_TYPE_TELEVISION. So to detect Android TV specifically, you can use this boolean check too: context.getPackageManager().hasSystemFeature("com.google.android.tv")

like image 76
IgorGanapolsky Avatar answered May 10 '23 23:05

IgorGanapolsky


TV

First check if the device is a TV or not. Here is how the documentation recommends doing it:

public static final String TAG = "DeviceTypeRuntimeCheck";

UiModeManager uiModeManager = (UiModeManager) getSystemService(UI_MODE_SERVICE);
if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) {
    Log.d(TAG, "Running on a TV Device")
} else {
    Log.d(TAG, "Running on a non-TV Device")
}

More reading

  • Building TV Apps
  • Building Layouts for TV
  • Designing for Android TV

Notes

  • As discouraged in the documentation, don't use the exact same layouts for TV as for phones and tablets.

Phone and Tablet

Make different resource files to be used with the various device sizes.

  • Phone - This can be the default.

  • Tablet - Use sw600dp or large to determine this.

See this answer for more information about this.

like image 39
Suragch Avatar answered May 11 '23 00:05

Suragch