Tablet or Phone - Android
Asked Answered
D

30

146

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)

Dight answered 29/4, 2011 at 13:0 Comment(9)
are you developing a native app or web app?? you can check for the width i.e dimensions of the phone that way you would have a rough idea whether it is tablet or a phone??Allopatric
I though about the "dimensions" but I tought tere my a a function. I tought you can read it out of the "About Phone" section.Dight
You are asking the wrong question. It does not matter whether the device is a phone, tablet, television, toaster, teacup, or thermometer. What matters are the capabilities, not the marketing-defined class of the device. Please ask a fresh Android question describing what capabilities you are seeking and how to detect whether the device has such capabilities, or how to filter yourself out of the Market for devices that lack such capabilities.Thayne
@CommonsWare: some times you want to add extra features for devices that have a larger screen.Mythological
@breceivemail: Which means you need to check whether the device has a larger screen. "Larger screen" != "tablet".Thayne
A better answer can be found here: https://mcmap.net/q/57042/-determine-if-the-device-is-a-smartphone-or-tablet-duplicate Simple as that :-)Epos
I think we have a pretty updated solution with this post on Android documentation. developer.android.com/guide/practices/… This rightly puts the difference between the 7" tablet and the 5"phone where we have all the confusion.Goyette
I would like to downvote this entire page! A phone does telephony, a tablet does not. Pretty much all suggestions are dirty hacks that no one should use. The world would be a better place if no one saw this page ever again!Prepay
Tablets do telephony these days, at least some of them. But the fact is that they are quickly dying out, see businessinsider.com/…. Kindle is the only tablet that is still successful. Meanwhile, TVs, watches, Chromebooks, VR headset, etc. also run Android so it's not a "tablet or phone" question.Swanhilda
W
123

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.

Waddell answered 17/1, 2013 at 0:11 Comment(4)
+1, great answer because it provides more insight into why you actually want to check for tablet/phone. We're approaching a moment in which phones will become small tablets anyway ;)Scenography
How this applies to large phones, such as the Galaxy Note and the new Nexus 6? By using this technique, will these large devices be detected as phones or tablets?Ashien
Unfortunately, this apporach does not work for the Samsung Mega 6.3 device and returns it as a tablet (sw600dp) - any other ideas to capture this?Snide
do tablets make phone calls?Starvation
D
65

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

Dreamworld answered 6/3, 2012 at 19:29 Comment(11)
On both - Kindle Fire and Motorola Droid Bionic -- the SCREENLAYOUT_SIZE_MASK == 15. So why would your solution work?Upstairs
I believe, this results true on the Kindle Fire. I dont have a bionic on me today...but I will check in a few days when my friend comes back into town. However.....I've been testing Helton Isac's answer and it works beautifully. Please check that too.Dreamworld
There's Configuration.SCREENLAYOUT_SIZE_XLARGE, so you don't have to use a constant, and you can use >= LARGE.Duckworth
Galaxy Note seems to report SCREENLAYOUT_SIZE_LARGE so it would be wrongly classified as tabletScalawag
@Scalawag this was not always the case. originally samsung had it misreporting its bucket size until a later ICS update/release.Dreamworld
@forgivegod That makes sense. The Galaxy Note in which I detected the issue was running Android 2.xScalawag
Your isTablet solution is e.g. not working on a Emulator with API 18 and Nexus 7 1200 x 1920 xhdpi !Saith
@Saith did you set the screensize to "large"?Dreamworld
I think not the size is to large. I have tested your code on Emulator and the result of "isTablet(Context context) was false. Try by self on Emulator.Saith
set the size to large, here are the specs for the 2013 edition of the nexus 7 : emirweb.com/ScreenDeviceStatistics.php#Header446Dreamworld
If the device font is small and display size is small in settings, this case is returned true.Sacred
D
40

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;
}
Dibble answered 8/3, 2012 at 20:58 Comment(9)
The best solution that i found, thank you Helton Isac! Perhaps can you add (for a better solution) a check for the inchs of the screen? anyway, a 10 for this solutionCollins
I really disagree. This is a method to find a certain screen size. Again, as I have answered, there IS NO difference between a tablet and a phone. This is not an answer to the question. It is not possible to differentiate because there is no 1 difference. If you need to code for certain features (like you seem to do for certain screen sizes), then do so, but do not call it tablet vs phone. Topic starter seemed to put the line @ certain tilt functionality. Read @commonware 's comment on the question thourougly.Dammar
I do agree with Nanne, but as I said, in my Application I need to show two panels if the screen are large enough to do it. And I can't use layouts in this case, because the screen logic was in the Java side.Dibble
Helton, thx for this. Thought I'd say that this returns: Kindle Fire : false, Moto Xoom (v1) : true, Galaxy Note : false, Galaxy Tab 10.1 limited : trueDreamworld
Aside from the argument, Configuration.SCREENLAYOUT_SIZE_XLARGE = 4 according to developer.android.com/reference/android/content/res/… which can be used instead for API level less than 9.Chak
Unfortunately this function reports my Galaxy Nexus as a tablet. The problem is that the manufacturers appear to be using different rules with layout parameters. :(Melbamelborn
Your condition fails KindleChasitychasm
Nexus 7 is a tablet but is classified as SCREENLAYOUT_SIZE_LARGEScalawag
This properly retusn Samsung Mega 6 as a phone but since the device still uses the resources from sw600dp layout folder it can cause other issues. It seems for the Mega 6 we just have to accept that it is essentially a tablet...Snide
L
12

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.

Loreanloredana answered 17/2, 2012 at 9:50 Comment(2)
This is not working... simply some phones report the wrong density values and the computation in inches fails - see there: #2193957Rabato
Well, I like 7' tablets (pocket size) and this answer is the best I think. But return (screenDiagonal >= 9.0 ); should be return (screenDiagonal >= 6.5 ). However dependent on the use as in commented in comments to the question.Marysa
D
11

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)

Dammar answered 29/4, 2011 at 13:2 Comment(15)
I've got problems with my tilt function and my new tablet (Transformer)Dight
Kind of a silly answer imo - of course there is a difference. Galaxy = phone. Why? Because it's a "smartphone" according to the manufacturer for one. If you're hinting that he needs to check for size, or ability to call, or... anything - just say that.Weatherbound
So something is a phone because the manufacturer says its a smartphone. But that's not really information you have available is it? If I wanted to say any of those things, I would have. But I didn't, because I can't read minds. If you read @Dight 's comment, it's about "tilt function". Why would I guess calling or screensize? The problem seems to be in tilt, and that has nothing to do with if the manufacturer calls it a "smartphone". Silly commentDammar
tilit work for mobiles but not for tablets, so I would make a custom tilit function for tablerts^^Dight
I disagree, it might not work for all mobiles, while some tablets do have these sensors. That's why my initial answer about no difference. Anyway, I've added some code you should try.Dammar
The problem is, that because tablets are "build" in landscape mode the x and y axis of the accelerometer are flipped when you expect your app to run in portrait mode. This can mess things up quite a bit :) So it IS vital that you check weather you are running on a tablet or not.Hypogeal
But then it is the other way around => if that is the only thing what makes a device a tablet, you should find out how the x/y axis works, not the other way around. I doubt by the way that this is true for all tablets and/or phones?Dammar
I know this is and old question, but now I'm into this, but @Nanne, it's not about how the orientation sensor works, it's about in "tablets", the reference axis is changed, comparing to "phones". So, let's say in a phone (0, 0, 0) is portrait mode and in a tablet (0,0,0) is landscape, that's why it's important. (the values are not real)Hullda
I disagree. Some tablets might, but this is not a defining feature of "tablets" at all. It has to do with landscape vs. portrait, not with tablets vs. phones. How about square screens? That would neither be a phone nor a tablet (although I suspect the flipout would be sad about that). Either way, and I am repeating myself here, you should check for the feature you want to check for, because "is it a tablet or a phone" is not something you can or should want to check.Dammar
@Nanne, I understand your point, but still, I think there should be a feature/property/way to determine whether the accelerometer X-axis correspond to the width of the device or the height. For some uses, you may need to map your layout with some axis of the accelerometer, the only way we had to do that was by assuming the following: portrait=> y-axis<->height, x-axis<->width; landscape, the otherway round. If this reference changes, it's more complex to control the layout.Hullda
What you say is correct, but the question is "is it a tablet or a phone", and your "issue" is about how accelerometer corresponds with the screen, which is not a guaranteed difference between a phone and a tablet, because there IS NO clear difference between them. What is a note? What is Tab? How do they define their screen/accels? Remember, we are talking about above question....Dammar
This doesn't seem right... I thought the definition of a "tablet" was an Android device with a large screen.Headmistress
Large how? In Inches? I've got a Yarvik tablet lying around that is way bigger then my phone in inches, but my phone has a lot more pixels. Programming issues either revolve around measurable things like amount of pixels, or around user/usage preferences, which should be a setting. A 1024x800 phone has the same screen issues as a tablet with that screensize, and a 800x600 tablet doesn't. Find out the density, find out the size, find out the features. Program according to that, but don't try to capture the world in "tablet" and "not tablet". It's too limiting.Dammar
Nanne, how would else would you suggest determining the difference in accelorometer X/Y mappings on some devices? Tablet vs. phone seems to associate with X/Y vs. Y/X mappings.Setup
You could probably check for screen rotation and current height/width form factor to determine if the default orientation is landscape or portrait, and go from there? Or, to get more detailed help, open a question here to ask how to find the accelerometer mapping out. THis is one of the things I was talking about: there is no phone vs tablet, there is however (apparently) x/y vs y/x mapping. If you want to know that, find that out. Don't find out some arbitrary "phone" vs "tablet", but find out what you want to find out:)Dammar
E
10

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";
}
Eisteddfod answered 14/6, 2012 at 21:22 Comment(1)
Some tablet can phone and have a GSM or CDMA type...So your solution is not perfect too.Trickle
A
9

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;
}
Allyn answered 19/2, 2018 at 12:57 Comment(1)
Or define in /res/values-sw600dp/attr.xml <bool name="isTablet">true</bool>Oil
S
8

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
}
Seraphic answered 14/9, 2012 at 2:26 Comment(0)
C
5

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

Compass answered 14/1, 2017 at 2:46 Comment(0)
C
3

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;
        }
        }
Cathartic answered 11/1, 2013 at 18:38 Comment(1)
what is the value of shortSize ?Edinburgh
R
3

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;
}
Repand answered 24/11, 2013 at 14:29 Comment(4)
This solution is e.g. not working on a Emulator with API 18 and Nexus 7 1200 x 1920 xhdpi !Saith
you should test on real device :)Repand
I have tested on Emulator and the result of "isTablet(Context context) was false. Try by self on Emulator.Saith
Thanks for this @hqt, I've just transcoded this to the C# needed for Xamarin Studio: public static bool isTablet (Context context) { return (context.Resources.Configuration.ScreenLayout & Android.Content.Res.ScreenLayout.SizeMask) >= Android.Content.Res.ScreenLayout.SizeLarge; } Berkey
L
2

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

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

cheers :-)

Lent answered 8/9, 2015 at 13:4 Comment(0)
M
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.)

Menefee answered 5/11, 2015 at 19:53 Comment(0)
P
1

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; 
}
Pattiepattin answered 24/4, 2012 at 6:10 Comment(3)
This solution is e.g. not working on a Emulator with API 18 and Nexus 7 1200 x 1920 xhdpi !Saith
This no longer works on some devices. For instance it returns false for Samsung Mega deviceSnide
Yeah.. This no longer work... I actually used to add boolean in all the string file for each folders values, values_large etc <bool name="isTablet">false</bool> <bool name="isLargeTablet">false</bool> and then check if R.bool.isTablet is true to find if the device is tabletPattiepattin
C
1

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

Collins answered 6/11, 2012 at 11:59 Comment(0)
S
1

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

Shooin answered 6/9, 2013 at 9:33 Comment(0)
J
0

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>
Jenine answered 15/8, 2013 at 3:23 Comment(0)
I
0

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!

Indian answered 24/9, 2014 at 23:13 Comment(1)
Explanation for -1 ? , this is a method recomended by google.Indian
T
0

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

Tahiti answered 8/1, 2015 at 5:1 Comment(0)
S
0

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 );
}
Stillborn answered 26/3, 2015 at 1:8 Comment(0)
T
0
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)));
    }
Tidy answered 15/5, 2015 at 10:38 Comment(0)
S
0

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

Snide answered 1/9, 2015 at 18:6 Comment(0)
D
0

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?

Doyen answered 18/12, 2018 at 7:45 Comment(0)
T
0

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.

Triboluminescent answered 16/8, 2019 at 14:55 Comment(0)
R
-1

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;
}
Roselleroselyn answered 22/11, 2011 at 5:49 Comment(2)
No longer valid with ICS. Indeed, there are tablets with Android versions below 11Hullda
This is NOT reliable. The new ICS phones have an API level > 11.Svetlana
S
-1

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.

Spite answered 21/2, 2012 at 23:12 Comment(4)
Not all tablets have a default landscape orientation. And if the "default" orientation matters to your program, it's probably wrong in other ways. See this Android Developers' Blog post for an example.Hen
Please, can you give specific examples of tablets, which in the default orientation the width is less than the height? And of course you know better what should be my app :D.Spite
The Nexus 7 would be one example. But you don't have to take my word for it: read the article I linked, which explains it all.Hen
I think should change the name of my method. In fact, more importantly (at least for my app ;) ) default device orientation, and my method is adequate for this task. Also very correctly identified the problem @Dammar answer, see above.Spite
L
-1

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;

Literate answered 7/7, 2012 at 19:56 Comment(1)
This is not right because Samsung galaxy s3 resultion 720 x 1280.Officious
F
-1

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);
Flounce answered 24/9, 2013 at 7:32 Comment(0)
E
-1

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;
    }
Emblazonment answered 8/10, 2017 at 15:39 Comment(0)
G
-3

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!

Grabble answered 29/4, 2011 at 13:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.