¿Cómo detectar el dispositivo es un teléfono Android o una tableta Android?


Tengo dos aplicaciones para tabletas Android y teléfonos Android. Para la aplicación de tableta configuré android:minSdkVersion="11". Pero hoy en día los teléfonos Android como Galaxy S3 tiene la versión de Android 4.0.4 para que los usuarios de S3 puedan descargar la aplicación de mi tableta desde Google Play Store. Quiero advertir a los usuarios de teléfonos que descarguen la aplicación del teléfono cuando instalen la aplicación de la tableta. Viceversa para los usuarios de tabletas descargue la aplicación de tableta cuando ejecutan la aplicación de teléfono.

¿Hay alguna forma fácil de detectar el tipo de dispositivo?

Editar:

Encontré una solución sobre esto enlace .

En el archivo de manifiesto se puede declarar la función de pantalla para el teléfono y tabletas a continuación, Google Play decide los permisos de descarga para el teléfono y la tableta.

Author: JJD, 2012-07-04

7 answers

Usa esto:

public static boolean isTablet(Context context) {
    return (context.getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK)
            >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}

Que devolverá true si el dispositivo está funcionando en una pantalla grande.

Algunos otros métodos útiles se pueden encontrar aquí.

 125
Author: Alex Lockwood,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-24 02:50:17

También puedes probar esto
Agregar parámetro booleano en el archivo de recursos.
en res / values / dimen.archivo xml añadir esta línea

<bool name="isTab">false</bool>

Mientras está en res/values-sw600dp/dimen.archivo xml añada esta línea:

<bool name="isTab">true</bool>

Entonces en su archivo java obtenga este valor:

if(getResources().getBoolean(R.bool.isTab)) {
    System.out.println("tablet");
} else {
    System.out.println("mobile");
}
 20
Author: Bhavana Vadodariya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-14 07:27:39

Este fragmento de código indicará si el tipo de dispositivo es de 7" pulgadas o más y Mdpi o una resolución más alta. Puede cambiar la implementación según su necesidad.

 private static boolean isTabletDevice(Context activityContext) {
        boolean device_large = ((activityContext.getResources().getConfiguration().screenLayout &
                Configuration.SCREENLAYOUT_SIZE_MASK) ==
                Configuration.SCREENLAYOUT_SIZE_LARGE);

        if (device_large) {
            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) {
                AppInstance.getLogger().logD("DeviceHelper","IsTabletDevice-True");
                return true;
            }
        }
        AppInstance.getLogger().logD("DeviceHelper","IsTabletDevice-False");
        return false;
    }
 7
Author: Pawan Maheshwari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-13 07:22:24

Use las capacidades de Google Play Store y solo habilite la descarga de su aplicación para tabletas en tabletas y la aplicación para teléfonos en teléfonos.

Si el usuario instala la aplicación incorrecta, debe haberla instalado utilizando otro método.

 0
Author: Marcio Covre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-04 14:22:48

Tuvimos el problema similar con nuestra aplicación que debe cambiar en función del tipo de dispositivo - Tab/Teléfono. IOS nos dio el tipo de dispositivo perfectamente, pero la misma idea no funcionaba con Android. el método resolution/ DPI falló con pequeñas pestañas res, teléfonos de alta resolución. después de un montón de pelos rasgados y golpeando nuestras cabezas sobre la pared, probamos una idea extraña y funcionó excepcionalmente bien que no dependerá de las resoluciones. esto debería ayudarte a ti también.

En la clase Principal, escribe esto y deberías obtenga su tipo de dispositivo como nulo para TAB y móvil para teléfono.

String ua=new WebView(this).getSettings().getUserAgentString();


if(ua.contains("Mobile")){
   //Your code for Mobile
}else{
   //Your code for TAB            
}
 0
Author: user3703142,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-03 13:49:53

Utilice el siguiente código para identificar el tipo de dispositivo.

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");
              Boolean r = (Boolean) mIsLayoutSizeAtLeast.invoke(con, 0x00000004); // Configuration.SCREENLAYOUT_SIZE_XLARGE
              return r;
         } catch (Exception x) {
              return false;
         }
      }
    return false;
}
 0
Author: Vaishali Sutariya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-21 13:26:13

Creo que esto debería detectar si algo es capaz de hacer una llamada telefónica, todo lo demás sería una tableta/TV sin capacidades de teléfono.

Por lo que he visto, esto es lo único que no depende de screensize.

public static boolean isTelephone(){
    //pseudocode, don't have the copy and paste here right know and can't remember every line
    return new Intent(ACTION_DIAL).resolveActivity() != null;
}
 -1
Author: HopefullyHelpful,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-20 00:04:29