Tuesday, December 24, 2013

How To Determine If Android Device Is a Tablet Or a Phone?

Setting your screen correctly for different size devices is one of the trickier things to get correct in Android.  The problem is that different devices report different sizes for the same screen size.  I've tried several different solutions for this and the best I found is one from Stackoverflow.

I added the code to a static method I can call where ever it is needed in the app.


public static boolean isTabletDevice(Context activityContext) 
{
        
        boolean xlarge = ((activityContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);

        if (xlarge) 
        {
            DisplayMetrics metrics = new DisplayMetrics();
            Activity activity = (Activity) activityContext;
            activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

            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) 
            {

                return true;
            }
        }

        return false;
}

Examples of how I've used this method can be found in the OpenStax College Android app.  The code is on Github. The method above is in the class OSCUtil. An example of using it is in the LandingActivity class.