问题
I would like to programmatically determine (on the Android platform), if the target device is a phone or a tablet. Is there a way to do this? I tried using Density Metrics to determine the resolution and used resources (images and layouts) accordingly but, it did not turn out well. There are differences when I launch the app on a phone (Droid X) and a tablet (Samsung Galaxy 10.1).
Please advise.
回答1:
You can use this 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;
}
Link: http://www.androidsnippets.com/how-to-detect-tablet-device
回答2:
As James has already mentioned, You can determine screen size programatically and use a threshold Number to differrentiate between your logic.
回答3:
Based on Aracem's answer, I updated the snippet with normal tablet check for 3.2 or higher (sw600dp):
public static boolean isTablet(Context context) {
try {
if (android.os.Build.VERSION.SDK_INT >= 13) { // Honeycomb 3.2
Configuration con = context.getResources().getConfiguration();
Field fSmallestScreenWidthDp = con.getClass().getDeclaredField("smallestScreenWidthDp");
return fSmallestScreenWidthDp.getInt(con) >= 600;
} else if (android.os.Build.VERSION.SDK_INT >= 11) { // Honeycomb 3.0
Configuration con = context.getResources().getConfiguration();
Method mIsLayoutSizeAtLeast = con.getClass().getMethod("isLayoutSizeAtLeast", int.class);
Boolean r = (Boolean) mIsLayoutSizeAtLeast.invoke(con, 0x00000004); // Configuration.SCREENLAYOUT_SIZE_XLARGE
return r;
}
} catch (Exception e) {
}
return false;
}
来源:https://stackoverflow.com/questions/7251131/how-to-determine-the-target-device-programmatically-in-android