国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

淺談android獲取設備唯一標識完美解決方案

2019-10-22 18:29:22
字體:
來源:轉載
供稿:網友

本文介紹了淺談android/233017.html">android/198545.html">android獲取設備唯一標識完美解決方案,分享給大家,具體如下:

/** * deviceID的組成為:渠道標志+識別符來源標志+hash后的終端識別符  *  * 渠道標志為:  * 1,andriod(a)  *  * 識別符來源標志:  * 1, wifi mac地址(wifi);  * 2, IMEI(imei);  * 3, 序列號(sn);  * 4, id:隨機碼。若前面的都取不到時,則隨機生成一個隨機碼,需要緩存。  *  * @param context  * @return  */ public static String getDeviceId(Context context) {  StringBuilder deviceId = new StringBuilder();  // 渠道標志  deviceId.append("a");  try {   //wifi mac地址   WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);   WifiInfo info = wifi.getConnectionInfo();   String wifiMac = info.getMacAddress();   if(!isEmpty(wifiMac)){    deviceId.append("wifi");    deviceId.append(wifiMac);    PALog.e("getDeviceId : ", deviceId.toString());    return deviceId.toString();   }   //IMEI(imei)   TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);   String imei = tm.getDeviceId();   if(!isEmpty(imei)){    deviceId.append("imei");    deviceId.append(imei);    PALog.e("getDeviceId : ", deviceId.toString());    return deviceId.toString();   }   //序列號(sn)   String sn = tm.getSimSerialNumber();   if(!isEmpty(sn)){    deviceId.append("sn");    deviceId.append(sn);    PALog.e("getDeviceId : ", deviceId.toString());    return deviceId.toString();   }   //如果上面都沒有, 則生成一個id:隨機碼   String uuid = getUUID(context);   if(!isEmpty(uuid)){    deviceId.append("id");    deviceId.append(uuid);    PALog.e("getDeviceId : ", deviceId.toString());    return deviceId.toString();   }  } catch (Exception e) {   e.printStackTrace();   deviceId.append("id").append(getUUID(context));  }  PALog.e("getDeviceId : ", deviceId.toString());  return deviceId.toString(); } /**  * 得到全局唯一UUID  */ public static String getUUID(Context context){  SharedPreferences mShare = getSysShare(context, "sysCacheMap");  if(mShare != null){   uuid = mShare.getString("uuid", "");  }  if(isEmpty(uuid)){   uuid = UUID.randomUUID().toString();   saveSysMap(context, "sysCacheMap", "uuid", uuid);  }  PALog.e(tag, "getUUID : " + uuid); return uuid; } 

有時需要對用戶設備進行標識,所以希望能夠得到一個穩定可靠并且唯一的識別碼。雖然Android系統中提供了這樣設備識別碼,但是由于android系統版本、廠商定制系統中的Bug等限制,穩定性和唯一性并不理想。而通過其他硬件信息標識也因為系統版本、手機硬件等限制存在不同程度的問題。

下面收集了一些“有能力”或“有一定能力”作為設備標識的串碼。

DEVICE_ID

這是Android系統為開發者提供的用于標識手機設備的串號,也是各種方法中普適性較高的,可以說幾乎所有的設備都可以返回這個串號,并且唯一性良好。

這個DEVICE_ID可以同通過下面的方法獲取:

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

假設我們確實需要用到真實設備的標識,可能就需要用到DEVICE_ID。在以前,我們的Android設備是手機,這個DEVICE_ID可以同通過TelephonyManager.getDeviceId()獲取,它根據不同的手機設備返回IMEI,MEID或者ESN碼,但它在使用的過程中會遇到很多問題:

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

MAC ADDRESS

可以使用手機Wifi或藍牙的MAC地址作為設備標識,但是并不推薦這么做,原因有以下兩點:

  • 硬件限制:并不是所有的設備都有Wifi和藍牙硬件,硬件不存在自然也就得不到這一信息。
  • 獲取的限制:如果Wifi沒有打開過,是無法獲取其Mac地址的;而藍牙是只有在打開的時候才能獲取到其Mac地址。

獲取Wifi Mac地址:

獲取藍牙 Mac地址:

Sim Serial Number

裝有SIM卡的Android 2.3設備,可以通過下面的方法獲取到Sim Serial Number:

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

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

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() 返回相同的值。
  • 它在Android <=2.1 or Android >=2.3的版本是可靠、穩定的,但在2.2的版本并不是100%可靠的

Serial Number

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

String SerialNumber = android.os.Build.SERIAL;  

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

Installtion ID

這種方式的原理是在程序安裝后第一次運行時生成一個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出來,通過內部算法保證盡量和設備硬件信息相關,以及標識的唯一性。

總結

綜合以上所述,為了實現在設備上更通用的獲取設備唯一標識,我們可以實現這樣的一個類,為每個設備產生唯一的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支持。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 杂多县| 铁岭县| 虎林市| 改则县| 凤城市| 宜兰市| 尉犁县| 巨野县| 五台县| 河西区| 施甸县| 横峰县| 灵寿县| 万山特区| 岐山县| 得荣县| 武陟县| 聊城市| 垣曲县| 双流县| 阜新| 伊川县| 荆门市| 吉木乃县| 望都县| 大英县| 冀州市| 濉溪县| 安塞县| 平利县| 玛纳斯县| 仲巴县| 水富县| 潮安县| 临邑县| 嵩明县| 汾西县| 五原县| 米易县| 荆州市| 鸡西市|