How to determine the target device programmatically in Android?

拈花ヽ惹草 提交于 2020-01-03 04:51:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!