Tablet or Phone - Android

后端 未结 30 2180
难免孤独
难免孤独 2020-11-22 08:33

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)

30条回答
  •  灰色年华
    2020-11-22 09:23

    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
    }
    

提交回复
热议问题