2010-06-25 13 views
8

¿Cómo obtengo una ID única de un teléfono Android?Identificación única de Android

Siempre que trato de obtener el ID único del teléfono como una cadena que siempre muestra Identificación del androide y no hay otros valores hex únicas.

¿Cómo consigo obtener ese?

Este es el código que utilizo para obtener el identificador hasta ahora:

String id=Settings.Secure.getString(contentResolver,Settings.Secure.ANDROID_ID); 
Log.i("Android is is:",id); 

la salida que me sale el siguiente aspecto:

Android id is: android id 

estoy usando un Nexus One para la prueba.

+0

posible duplicado de [¿Hay ¿una identificación de dispositivo Android única?] (http://stackoverflow.com/questions/2785485/is-there-a-unique-android-device-id) –

+0

Ver http://stackoverflow.com/questions/2785485/is -there-a-unique-android-de vice-id – MatejC

+0

mejor manera de obtener el ID teléfonos Android se afirma [aquí] [1] [1]: http://stackoverflow.com/questions/4468248/unique-id-of-android- device/23196094 # 23196094 – Nepster

Respuesta

4
((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId(); 

con manifiesta

<uses-permission android:name='android.permission.READ_PHONE_STATE' /> 

Editar:

Aquí es una lectura interesante acerca de la Identificación del androide:

How to set the Android ID

Android ID Requires Market Login

Intenta configurarlo en algo que no sea 'ID de Android' y mira si lees el nuevo valor.

+1

Gracias por su respuesta, pero quiero una ID única de 32 bits en getDeviceID() solo tengo 15 caracteres, entonces, ¿cómo puedo obtener la identificación HMAC MD5 de 32 bits del dispositivo Android? – jaimin

+2

Tenga en cuenta que existen grandes limitaciones con esta solución: http://android-developers.blogspot.com/2011/03/identifying-app-installations.html – emmby

+1

¿Qué pasa si esto se ejecuta en una tableta sin un teléfono? – Chloe

1

La dirección MAC inalámbrica es más exclusiva que IMEI, ya que la última se vuelve falsa en los dispositivos robados. El inconveniente es que solo funciona en dispositivos habilitados para WiFi. WifiInfo

+0

Tenga en cuenta que existen enormes limitaciones con esta solución: http://android-developers.blogspot.com/2011/03/identifying-app-installations.html – emmby

+0

Muchos teléfonos que he probado (30%) devuelve 'null' para la dirección Mac en cualquier situación. * Algunos teléfonos * solo pueden informarlo cuando la conexión wifi está activada. – JoJo

2

Aquí está el segmento de código de cómo obtener androidId, único ID de dispositivo y número de serie para su teléfono Android puede ser que lo ayude.

TelephonyManager tm = (TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE); 
      final String DeviceId, SerialNum, androidId; 
      DeviceId = tm.getDeviceId(); 
      SerialNum = tm.getSimSerialNumber(); 
      androidId = Secure.getString(getContentResolver(),Secure.ANDROID_ID); 

      UUID deviceUuid = new UUID(androidId.hashCode(), ((long)DeviceId.hashCode() << 32) | SerialNum.hashCode()); 
      String mydeviceId = deviceUuid.toString(); 
      Log.v("My Id", "Android DeviceId is: " +DeviceId); 
      Log.v("My Id", "Android SerialNum is: " +SerialNum); 
      Log.v("My Id", "Android androidId is: " +androidId); 
16

Para obtener instrucciones detalladas sobre cómo obtener un identificador único para cada dispositivo Android de su aplicación se instala desde, consulte este funcionario Desarrolladores de Android de Publicación:

http://android-developers.blogspot.com/2011/03/identifying-app-installations.html

parece que la mejor manera es para que generes uno tú mismo al momento de la instalación y luego lo leas cuando se relanza la aplicación.

Encuentro personalmente aceptable pero no ideal. Ningún identificador proporcionado por Android funciona en todas las instancias, ya que la mayoría depende de los estados de la radio del teléfono (wifi activado/desactivado, activación/desactivación de la conexión móvil, activación/desactivación de bluetooth). Los otros, como Settings.Secure.ANDROID_ID, deben ser implementados por el fabricante y no se garantiza que sean únicos.

El siguiente es un ejemplo de escribir datos en un archivo de INSTALACIÓN que se almacenaría junto con cualquier otro dato que la aplicación guarde localmente.

public class Installation { 
    private static String sID = null; 
    private static final String INSTALLATION = "INSTALLATION"; 

    public synchronized static String id(Context context) { 
     if (sID == null) { 
      File installation = new File(context.getFilesDir(), INSTALLATION); 
      try { 
       if (!installation.exists()) 
        writeInstallationFile(installation); 
       sID = readInstallationFile(installation); 
      } catch (Exception e) { 
       throw new RuntimeException(e); 
      } 
     } 
     return sID; 
    } 

    private static String readInstallationFile(File installation) throws IOException { 
     RandomAccessFile f = new RandomAccessFile(installation, "r"); 
     byte[] bytes = new byte[(int) f.length()]; 
     f.readFully(bytes); 
     f.close(); 
     return new String(bytes); 
    } 

    private static void writeInstallationFile(File installation) throws IOException { 
     FileOutputStream out = new FileOutputStream(installation); 
     String id = UUID.randomUUID().toString(); 
     out.write(id.getBytes()); 
     out.close(); 
    } 
} 
1
Settings.Secure.getString(contentResolver,Settings.Secure.ANDROID_ID); 

esto no es un buen método que devolverá un valor nulo en algunos casos.

este pedazo de código le ayudará a generar la identificación única pseudodevice ....... ``

public String getDeviceID() { 

/*String Return_DeviceID = USERNAME_and_PASSWORD.getString(DeviceID_key,"Guest"); 
return Return_DeviceID;*/ 

TelephonyManager TelephonyMgr = (TelephonyManager) getApplicationContext().getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE); 
String m_szImei = TelephonyMgr.getDeviceId(); // Requires 
// READ_PHONE_STATE 

// 2 compute DEVICE ID 
String m_szDevIDShort = "35" 
+ // we make this look like a valid IMEI 
Build.BOARD.length() % 10 + Build.BRAND.length() % 10 
+ Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 
+ Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 
+ Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 
+ Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 
+ Build.TAGS.length() % 10 + Build.TYPE.length() % 10 
+ Build.USER.length() % 10; // 13 digits 
// 3 android ID - unreliable 
String m_szAndroidID = Secure.getString(getContentResolver(),Secure.ANDROID_ID); 
// 4 wifi manager, read MAC address - requires 
// android.permission.ACCESS_WIFI_STATE or comes as null 
WifiManager wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
String m_szWLANMAC = wm.getConnectionInfo().getMacAddress(); 
// 5 Bluetooth MAC address android.permission.BLUETOOTH required 
BluetoothAdapter m_BluetoothAdapter = null; // Local Bluetooth adapter 
m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
String m_szBTMAC = m_BluetoothAdapter.getAddress(); 
System.out.println("m_szBTMAC "+m_szBTMAC); 

// 6 SUM THE IDs 
String m_szLongID = m_szImei + m_szDevIDShort + m_szAndroidID+ m_szWLANMAC + m_szBTMAC; 
System.out.println("m_szLongID "+m_szLongID); 
MessageDigest m = null; 
try { 
m = MessageDigest.getInstance("MD5"); 
} catch (NoSuchAlgorithmException e) { 
e.printStackTrace(); 
       } 
m.update(m_szLongID.getBytes(), 0, m_szLongID.length()); 
byte p_md5Data[] = m.digest(); 

String m_szUniqueID = new String(); 
for (int i = 0; i < p_md5Data.length; i++) { 
int b = (0xFF & p_md5Data[i]); 
// if it is a single digit, make sure it have 0 in front (proper 
// padding) 
if (b <= 0xF) 
m_szUniqueID += "0"; 
// add number to string 
m_szUniqueID += Integer.toHexString(b); 
} 
m_szUniqueID = m_szUniqueID.toUpperCase(); 

Log.i("-------------DeviceID------------", m_szUniqueID); 
Log.d("DeviceIdCheck", "DeviceId that generated MPreferenceActivity:"+m_szUniqueID); 

return m_szUniqueID; 

} 
+1

Esto puede ser único pero no es seguro de usar porque si el usuario hizo un restablecimiento de fábrica, el valor de Secure.ANDREID_ID (podría) se modificó para que el método devuelva una ID única diferente en comparación con la que se devolvió antes del restablecimiento de fábrica. –

0

Steam ID

Info adInfo = null; 

  

try { 

     adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext); 

} catch (IOException e) { 

     ... 

} catch (GooglePlayServicesAvailabilityException e) { 

     ... 

} catch (GooglePlayServicesNotAvailableException e) { 

     ... 

} 

  

String AdId = adInfo.getId(); 

Cuestiones relacionadas