獲取Android設備惟一標識碼

概述

有時須要對用戶設備進行標識,因此但願可以獲得一個穩定可靠而且惟一的識別碼。雖然Android系統中提供了這樣設備識別碼,可是因爲Android系統版本、廠商定製系統中的Bug等限制,穩定性和惟一性並不理想。而經過其餘硬件信息標識也由於系統版本、手機硬件等限制存在不一樣程度的問題。java

下面收集了一些「有能力」或「有必定能力」做爲設備標識的串碼。linux

DEVICE_ID

這是Android系統爲開發者提供的用於標識手機設備的串號,也是各類方法中普適性較高的,能夠說幾乎全部的設備均可以返回這個串號,而且惟一性良好。android

這個DEVICE_ID能夠同經過下面的方法獲取:算法

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); String DEVICE_ID = tm.getDeviceId(); 

它會根據不一樣的手機設備返回IMEI,MEID或者ESN碼,但在使用的過程當中有如下問題:shell

  • 非手機設備:最開始搭載Android系統都手機設備,而如今也出現了非手機設備:如平板電腦、電子書、電視、音樂播放器等。這些設備沒有通話的硬件功能,系統中也就沒有TELEPHONY_SERVICE,天然也就沒法經過上面的方法得到DEVICE_ID。
  • 權限問題:獲取DEVICE_ID須要READ_PHONE_STATE權限,若是隻是爲了獲取DEVICE_ID而沒有用到其餘的通話功能,申請這個權限一來大才小用,二來部分用戶會懷疑軟件的安全性。
  • 廠商定製系統中的Bug:少數手機設備上,因爲該實現有漏洞,會返回垃圾,如:zeros或者asterisks

MAC ADDRESS

可使用手機Wifi或藍牙的MAC地址做爲設備標識,可是並不推薦這麼作,緣由有如下兩點:安全

  • 硬件限制:並非全部的設備都有Wifi和藍牙硬件,硬件不存在天然也就得不到這一信息。
  • 獲取的限制:若是Wifi沒有打開過,是沒法獲取其Mac地址的;而藍牙是隻有在打開的時候才能獲取到其Mac地址。

獲取Wifi Mac地址:網絡

獲取藍牙 Mac地址:app

Sim Serial Number

裝有SIM卡的設備,能夠經過下面的方法獲取到Sim Serial Number:框架

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); String SimSerialNumber = tm.getSimSerialNumber(); 

注意:對於CDMA設備,返回的是一個空值!less

ANDROID_ID

在設備首次啓動時,系統會隨機生成一個64位的數字,並把這個數字以16進制字符串的形式保存下來,這個16進制的字符串就是ANDROID_ID,當設備被wipe後該值會被重置。能夠經過下面的方法獲取:

import android.provider.Settings;   String ANDROID_ID = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID); 

ANDROID_ID能夠做爲設備標識,但須要注意:

  • 廠商定製系統的Bug:不一樣的設備可能會產生相同的ANDROID_ID:9774d56d682e549c。
  • 廠商定製系統的Bug:有些設備返回的值爲null。
  • 設備差別:對於CDMA設備,ANDROID_ID和TelephonyManager.getDeviceId() 返回相同的值。

Serial Number

Android系統2.3版本以上能夠經過下面的方法獲得Serial Number,且非手機設備也能夠經過該接口獲取。

String SerialNumber = android.os.Build.SERIAL; 

Installtion ID

以上幾種方式都或多或少存在必定的侷限性或者Bug,若是並非確實須要對硬件自己進行綁定,使用本身生成的UUID也是一個不錯的選擇,由於該方法無需訪問設備的資源,也跟設備類型無關。

這種方式的原理是在程序安裝後第一次運行時生成一個ID,該方式和設備惟一標識不同,不一樣的應用程序會產生不一樣的ID,同一個程序從新安裝也會不一樣。因此這不是設備的惟一ID,可是能夠保證每一個用戶的ID是不一樣的。能夠說是用來標識每一份應用程序的惟一ID(即Installtion ID),能夠用來跟蹤應用的安裝數量等。

Google Developer Blog提供了這樣的一個框架:

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(); } } 

設備惟一ID

上文能夠看出,Android系統中並無能夠可靠獲取全部廠商設備惟一ID的方法,各個方法都有本身的使用範圍和侷限性,這也是目前流行的Android系統版本過多,設備也是來自不一樣廠商,且沒有統一標準等緣由形成的。

從目前發展來看,Android系統多版本共存還會持續較長的時間,而Android系統也不會被某個設備生產廠商壟斷,長遠看Android基礎系統將會趨於穩定,設備標識也將會做爲系統基礎部分而標準化,屆時這一問題纔有望完全解決。

目前的解決辦法,比較可行的是一一適配,在保證大多數設備方便的前提下,若是獲取不到,使用其餘備選信息做爲標識,即本身再封裝一個設備ID出來,經過內部算法保證儘可能和設備硬件信息相關,以及標識的惟一性。

 

 

android 底層是 Linux,咱們仍是用Linux的方法來獲取:


1 cpu號:

文件在: /proc/cpuinfo

經過Adb shell 查看:

adb shell cat /proc/cpuinfo

2 mac 地址

文件路徑 /sys/class/net/wlan0/address

adb shell  cat /sys/class/net/wlan0/address                              
xx:xx:xx:xx:xx:aa

這樣能夠獲取二者的序列號,


方法肯定,剩下的就是寫代碼了

以Mac地址爲例:

        String getMac() {
                String macSerial = null;
                String str = "";
                try {
                        Process pp = Runtime.getRuntime().exec(
                                        "cat /sys/class/net/wlan0/address ");
                        InputStreamReader ir = new InputStreamReader(pp.getInputStream());
                        LineNumberReader input = new LineNumberReader(ir);


                        for (; null != str;) {
                                str = input.readLine();
                                if (str != null) {
                                        macSerial = str.trim();// 去空格
                                        break;
                                }
                        }
                } catch (IOException ex) {
                        // 賦予默認值
                        ex.printStackTrace();
                }
                return macSerial;
        }

 

 

 

Android 手機上獲取物理惟一標識碼

惟一標識碼這東西在網絡應用中很是有用,例如檢測是否重複註冊之類的。

import android.provider.Settings.Secure;
private String android_id = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);

 

咱們在項目過程當中或多或少會使用到設備的惟一識別碼,咱們但願可以獲得一個穩定、可靠的設備惟一識別碼。今天咱們將介紹幾種方式。

       1. DEVICE_ID

 

假設咱們確實須要用到真實設備的標識,可能就須要用到DEVICE_ID。在之前,咱們的Android設備是手機,這個DEVICE_ID能夠同經過TelephonyManager.getDeviceId()獲取,它根據不一樣的手機設備返回IMEI,MEID或者ESN碼,但它在使用的過程當中會遇到不少問題:

  • 非手機設備: 若是隻帶有Wifi的設備或者音樂播放器沒有通話的硬件功能的話就沒有這個DEVICE_ID
  • 權限: 獲取DEVICE_ID須要READ_PHONE_STATE權限,但若是咱們只爲了獲取它,沒有用到其餘的通話功能,那這個權限有點大才小用
  • bug:在少數的一些手機設備上,該實現有漏洞,會返回垃圾,如:zeros或者asterisks的產品

 

        2. MAC ADDRESS

 

咱們也能夠經過手機的Wifi或者藍牙設備獲取MAC ADDRESS做爲DEVICE ID,可是並不建議這麼作,由於並非全部的設備都有Wifi,而且,若是Wifi沒有打開,那硬件設備沒法返回MAC ADDRESS.

 

        3. Serial Number

在Android 2.3能夠經過android.os.Build.SERIAL獲取,非手機設備能夠經過該接口獲取。

        4. ANDROID_ID

ANDROID_ID是設備第一次啓動時產生和存儲的64bit的一個數,當設備被wipe後該數重置

ANDROID_ID彷佛是獲取Device ID的一個好選擇,但它也有缺陷:

 

  • 它在Android <=2.1 or Android >=2.3的版本是可靠、穩定的,但在2.2的版本並非100%可靠的
  • 在主流廠商生產的設備上,有一個很常常的bug,就是每一個設備都會產生相同的ANDROID_ID:9774d56d682e549c

 

        5. Installtion ID : UUID

以上四種方式都有或多或少存在的必定的侷限性或者bug,在這裏,有另一種方式解決,就是使用UUID,該方法無需訪問設備的資源,也跟設備類型無關。

這種方式是經過在程序安裝後第一次運行後生成一個ID實現的,但該方式跟設備惟一標識不同,它會由於不一樣的應用程序而產生不一樣的ID,而不是設備惟一ID。所以常常用來標識在某個應用中的惟一ID(即Installtion ID),或者跟蹤應用的安裝數量。很幸運的,Google Developer Blog提供了這樣的一個框架:

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();
    }
}

   總結

綜合以上所述,爲了實如今設備上更通用的獲取設備惟一標識,咱們能夠實現這樣的一個類,爲每一個設備產生惟一的UUID,以ANDROID_ID爲基礎,在獲取失敗時以TelephonyManager.getDeviceId()爲備選方法,若是再失敗,使用UUID的生成策略。

重申下,如下方法是生成Device ID,在大多數狀況下Installtion ID可以知足咱們的需求,可是若是確實須要用到Device ID,那能夠經過如下方式實現:

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,
                        // 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;
    }
}

如何獲取Android手機的惟一標識?

代碼: 這裏是你在Android裏讀出 惟一的 IMSI-ID / IMEI-ID 的方法。 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 

注:android.os.SystemProperties的標籤被打上@hide了,因此sdk中並不會存在。若是須要使用,須要有android的source code支持。
相關文章
相關標籤/搜索