Get the Android device unique ID code

Source: Internet
Author: User
Tags unique id

Overview

Sometimes the user device needs to be identified, so you want to get a stable and reliable and unique identification code. Although such device identifiers are available in the Android system, stability and uniqueness are not ideal due to limitations such as the Android version and bugs in the vendor-specific system. And through other hardware information identification also because of the system version, mobile phone hardware and other limitations there are different degrees of problems.

The following collection of "capable" or "capable" as a device identification of the serial code.

device_id

This is an Android system for developers to identify the serial number of mobile devices, but also a variety of methods of high universality, it can be said that almost all devices can return this serial number, and the uniqueness of good.

This device_id can be obtained with the following methods:

It will return the Imei,meid or ESN code depending on the phone device, but the following problems are used in the process:

    • Non-mobile devices: Android devices are the first to be installed, and now there are non-mobile devices: such as tablets, ebooks, TVs, music players and so on. These devices do not have the hardware function of the call, there is no telephony_service in the system, and naturally it is impossible to obtain device_id by the above method.
    • Permission problem: Get device_id need read_phone_state permission, if just to get device_id and no other call function, request this permission to a large only small use, two deploy users will suspect the security of the software.
    • Bug in vendor-specific system: a few mobile devices, because of the implementation of the vulnerability, will return garbage, such as: zeros or asterisks
MAC ADDRESS

You can use your phone's WiFi or Bluetooth MAC address as your device ID, but this is not recommended for the following two reasons:

    • Hardware limitations: Not all devices have WiFi and Bluetooth hardware, the hardware does not exist naturally will not get this information.
    • Gets the limit: If WiFi is not turned on, it cannot get its MAC address, while Bluetooth is only available when it is opened to its MAC address.

Get WiFi MAC Address:

Get Bluetooth MAC Address:

Sim Serial Number

Device with SIM card, you can get to sim Serial number by the following method:

Note: For CDMA devices, a null value is returned!

android_id

When the device first starts, the system randomly generates a 64-bit number and saves the number in the form of a 16 string, which is a 16-android_id string that is reset when the device is wipe. The following methods can be obtained:

Import android.provider.Settings;   

The android_id can be used as a device identification, but it is important to note:

    • Vendor-Customized system bug: Different devices may produce the same android_id:9774d56d682e549c.
    • Vendor-Customized system bug: Some devices return a value of NULL.
    • Device differences: For CDMA devices, android_id and Telephonymanager.getdeviceid () return the same values.
Serial number

Android System version 2.3 and above can be obtained by the following method serial number, and non-mobile devices can also be obtained through the interface.

Installtion ID

There are some limitations or bugs in some of these ways, and if you do not really need to bind the hardware itself, using your own generated UUID is a good choice, because it does not require access to the device's resources, and is not related to the device type.

The principle of this approach is to generate an ID when the program is installed the first time it is run, which differs from the device's unique identity, and different applications produce different IDs, and the same program can be reinstalled differently. So this is not the device's unique ID, but it guarantees that each user's ID will be different. It can be said to be used to identify the unique ID of each application (that is, the Installtion ID), which can be used to track the number of apps installed.

Google Developer Blog provides such a framework:

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.getfile SDir (), 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 Randomac Cessfile (Installation, "R"); byte[] bytes = new byte[(int) f.length ()]; f.readfully (bytes); F.close (); return new String (bytes); }   
Device Unique ID

As can be seen above, the Android system does not have reliable access to all vendor device unique ID method, each method has its own scope of use and limitations, this is currently popular Android system version too many, equipment is from different manufacturers, and no unified standards and other reasons.

From the current development, the multi-version of the Android system will continue to coexist for a long time, and Android system will not be a monopoly of a device manufacturer, the long-term Android infrastructure will be stable, equipment identification will be the system as a basic part of the standardization, The issue is expected to be completely resolved.

The current solution, more feasible is one by one adaptation, in the premise of ensuring that most devices are convenient, if not obtained, using other alternative information as the identity, that is, to encapsulate a device ID itself, through the internal algorithm to ensure that as far as possible with the device hardware information related, as well as the uniqueness of the identity.

Android is Linux at the bottom, and we use Linux to get it:

1 CPU Number:

Files in:/proc/cpuinfo

View via adb shell:

ADB Shell Cat/proc/cpuinfo

2 MAC Address

File path/sys/class/net/wlan0/address

ADB Shell cat/sys/class/net/wlan0/address XX:XX:XX:XX:XX:AA

This will get the serial number of both,

Method is OK, the rest is to write the code

Take the MAC address as an example:

        String Getmac () {                 String macserial = null;                 String str = "";                 try {                          Process pp = Runtime.getruntime (). EXEC (                                          "Cat/sys/class/net/wlan0/address");                          InputStreamReader ir = newInputStreamReader (Pp.getinputstream ());                          LineNumberReader input = new LineNumberReader (IR);

                         for (; null! = str;) {                                 str = input.readline ();                                  if (str! = null) {                                          Macserial = Str.trim ();//Go to space                                          break;                                 }                         }                 catch (IOException ex ) {                        //give default values                          Ex.printstacktrace ();                }                  return macserial;        }

Get a physical unique ID on your Android phone

Unique identification code This is useful in Web applications, such as checking for duplicate registrations.
Import Android.provider.Settings.Secure; Private String android_id = secure.getstring (GetContext (). Getcontentresolver (), secure.android_id);

We will use the unique identification code of the device more or less in the course of the project, we hope to get a stable and reliable device unique identification code. Today we will cover several ways.

1. device_id

Assuming we do need to use the identity of the real device, we may need to use device_id. In the past, our Android device is a mobile phone, this device_id can be obtained by Telephonymanager.getdeviceid (), it returns Imei,meid or ESN code according to different mobile devices, However, it will encounter many problems in the process of use:

    • Non-mobile devices: If only the device with WiFi or the music player does not have the hardware function of the call, there is no such device_id
    • Permissions: Get device_id need read_phone_state permission, but if we just to get it, no other call function, then this permission is a bit large to small use
    • BUG: On a small number of mobile devices, the implementation has a loophole, will return garbage, such as: zeros or asterisks products

2. MAC ADDRESS

We can also get the MAC address as the device ID from the phone's WiFi or Bluetooth device, but it is not recommended because not all devices have WiFi and if WiFi is not turned on, the hardware device cannot return to MAC address.

3. Serial number

The Android 2.3 can be obtained via Android.os.Build.SERIAL, and non-mobile devices can be obtained through this interface.

4. android_id

ANDROID_ID is a number of 64bit that is generated and stored when the device is first started and resets when the device is wipe

ANDROID_ID seems to be a good choice to get a device ID, but it's also flawed:

    • It is reliable and stable in Android <=2.1 or Android >=2.3 version, but the version in 2.2 is not 100% reliable
    • In the mainstream manufacturers of equipment, there is a very frequent bug, that every device will produce the same android_id:9774d56d682e549c

5. Installtion Id:uuid

The above four ways have a certain limitation or bug, here, there is another way to solve, is to use the UUID, the method does not need to access the resources of the device, and is not related to the device type.

This is done by generating an ID after the first run of the program installation, but unlike the device's unique identity, it produces different IDs for different applications than the device unique IDs. This is often used to identify a unique ID in an app (that is, the Installtion ID), or to track the number of installs of an app. Fortunately, Google Developer blog provides such a framework:

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 Random         Accessfile (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 Fileo         Utputstream (installation);         String id = uuid.randomuuid (). toString ();         Out.write (Id.getbytes ());     Out.close (); } }

Summarize

In general, in order to achieve a more general acquisition device unique identity on the device, we can implement a class that produces a unique UUID for each device, based on android_id, with Telephonymanager.getdeviceid () when the acquisition fails For alternative methods, if you fail again, use the build strategy of the UUID.

Again, the following approach is to generate the device ID, in most cases the Installtion ID will meet our needs, but if you do need a device ID, it can be done in the following ways:

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 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,   & nbsp;                     //Unless it ' s not available, then fallback on a random number which we store     & nbsp;                   /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 was "very highly likely"      * to being unique across all Android devices.  Mu CH than android_id is.      *      * The UUID is generated by using android_id as the base key if APPROPR Iate, falling back on      * Telephonymanager.getdeviceid () If android_id are known to being incorrect, an D finally falling back      * on a random UUID that's persisted to sharedpreferences if Getdeviceid () Does not return a      * usable value.      *      * In some rare circumstances, the this ID is change.  in particular, If the device is factory reset a new device ID      * could be generated.  In addition, if a user Upgrades their phone from certain buggy implementationsof 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 which has neither a proper Android ID nor a device ID, t The his ID could change on reinstallation.      *      * Note that if the code falls-on using Telephonymanager.getdevice ID (), the resulting ID would not      * change after a factory reset.  Something to be aware of.      *      * Works around a bug in Android 2.2 for many devices when using Androi D_ID directly.      *      * @see  http://code.google.com/p/android/issues/detail?id= 10603      *      * @return A UUID that is used to uniquely identify your Devi Ce for most purposes.      */    public UUID Getdeviceuuid () {        return UUID;    }}

How do I get a unique ID for my Android phone?

Code: Here's how you read the only Imsi-id/imei-id on Android.  Java:string Myimsi = Android.os.SystemProperties.get (Android.telephony.TelephonyProperties.PROPERTY_IMSI); Within my emulator it returns:310995000000000
String Myimei = Android.os.SystemProperties.get (Android.telephony.TelephonyProperties.PROPERTY_IMEI); Within my emulator it returns:000000000000000

Note: The Android.os.SystemProperties label is @hide, so the SDK does not exist. If you need to use it, you need to have Android source code support.

Get the Android device unique ID code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.