¿Cómo encontrar el número de serie de un dispositivo Android?

Resuelto Eno asked hace 54 años • 17 respuestas

Necesito usar una identificación única para una aplicación de Android y pensé que el número de serie del dispositivo sería un buen candidato. ¿Cómo recupero el número de serie de un dispositivo Android en mi aplicación?

Eno avatar Jan 01 '70 08:01 Eno
Aceptado
TelephonyManager tManager = (TelephonyManager)myActivity.getSystemService(Context.TELEPHONY_SERVICE);
String uid = tManager.getDeviceId();

getSystemService es un método de la clase Actividad. getDeviceID() devolverá el MDN o MEID del dispositivo dependiendo de qué radio utilice el teléfono (GSM o CDMA).

Cada dispositivo DEBE devolver un valor único aquí (suponiendo que sea un teléfono). Esto debería funcionar para cualquier dispositivo Android con ranura SIM o radio CDMA. Estás solo con ese microondas con Android ;-)

haseman avatar Feb 23 '2010 23:02 haseman

Como menciona Dave Webb, el blog para desarrolladores de Android tiene un artículo que cubre esto.

Hablé con alguien de Google para obtener aclaraciones adicionales sobre algunos elementos. Esto es lo que descubrí y que NO se menciona en la publicación del blog antes mencionada:

  • ANDROID_ID es la solución preferida. ANDROID_ID es perfectamente confiable en versiones de Android <=2.1 o >=2.3. Sólo 2.2 tiene los problemas mencionados en la publicación.
  • Varios dispositivos de varios fabricantes se ven afectados por el error ANDROID_ID en 2.2.
  • Hasta donde he podido determinar, todos los dispositivos afectados tienen el mismo ANDROID_ID , que es 9774d56d682e549c . Que también es la misma identificación de dispositivo informada por el emulador, por cierto.
  • Google cree que los fabricantes de equipos originales han solucionado el problema en muchos o la mayoría de sus dispositivos, pero pude verificar que, al menos a principios de abril de 2011, todavía es bastante fácil encontrar dispositivos que tengan el ANDROID_ID roto.

Según las recomendaciones de Google, implementé una clase que generará un UUID único para cada dispositivo, usando ANDROID_ID como semilla cuando corresponda, recurriendo a TelephonyManager.getDeviceId() según sea necesario y, si eso falla, recurriendo a un UUID único generado aleatoriamente. que persiste durante los reinicios de la aplicación (pero no en las reinstalaciones de la aplicación).

import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

public class DeviceUuidFactory {

    protected static final String PREFS_FILE = "device_id.xml";
    protected static final String PREFS_DEVICE_ID = "device_id";
    protected static volatile UUID uuid;

    public DeviceUuidFactory(Context context) {
        if (uuid == null) {
            synchronized (DeviceUuidFactory.class) {
                if (uuid == null) {
                    final SharedPreferences prefs = context
                            .getSharedPreferences(PREFS_FILE, 0);
                    final String id = prefs.getString(PREFS_DEVICE_ID, null);
                    if (id != null) {
                        // Use the ids previously computed and stored in the
                        // prefs file
                        uuid = UUID.fromString(id);
                    } else {
                        final String androidId = Secure.getString(
                            context.getContentResolver(), Secure.ANDROID_ID);
                        // Use the Android ID unless it's broken, in which case
                        // fallback on deviceId,
                        // unless it's not available, then fallback on a random
                        // number which we store to a prefs file
                        try {
                            if (!"9774d56d682e549c".equals(androidId)) {
                                uuid = UUID.nameUUIDFromBytes(androidId
                                        .getBytes("utf8"));
                            } else {
                                final String deviceId = ((TelephonyManager) 
                                        context.getSystemService(
                                            Context.TELEPHONY_SERVICE))
                                            .getDeviceId();
                                uuid = deviceId != null ? UUID
                                        .nameUUIDFromBytes(deviceId
                                                .getBytes("utf8")) : UUID
                                        .randomUUID();
                            }
                        } catch (UnsupportedEncodingException e) {
                            throw new RuntimeException(e);
                        }
                        // Write the value out to the prefs file
                        prefs.edit()
                                .putString(PREFS_DEVICE_ID, uuid.toString())
                                .commit();
                    }
                }
            }
        }
    }

    /**
     * Returns a unique UUID for the current android device. As with all UUIDs,
     * this unique ID is "very highly likely" to be unique across all Android
     * devices. Much more so than ANDROID_ID is.
     * 
     * The UUID is generated by using ANDROID_ID as the base key if appropriate,
     * falling back on TelephonyManager.getDeviceID() if ANDROID_ID is known to
     * be incorrect, and finally falling back on a random UUID that's persisted
     * to SharedPreferences if getDeviceID() does not return a usable value.
     * 
     * In some rare circumstances, this ID may change. In particular, if the
     * device is factory reset a new device ID may be generated. In addition, if
     * a user upgrades their phone from certain buggy implementations of Android
     * 2.2 to a newer, non-buggy version of Android, the device ID may change.
     * Or, if a user uninstalls your app on a device that has neither a proper
     * Android ID nor a Device ID, this ID may change on reinstallation.
     * 
     * Note that if the code falls back on using TelephonyManager.getDeviceId(),
     * the resulting ID will NOT change after a factory reset. Something to be
     * aware of.
     * 
     * Works around a bug in Android 2.2 for many devices when using ANDROID_ID
     * directly.
     * 
     * @see http://code.google.com/p/android/issues/detail?id=10603
     * 
     * @return a UUID that may be used to uniquely identify your device for most
     *         purposes.
     */
    public UUID getDeviceUuid() {
        return uuid;
    }
}
emmby avatar Apr 11 '2011 19:04 emmby