如何唯一确定一台 Android 设备?

地址http://www.jianshu.com/p/868147a1b745

高票答案4

考察了众多唯一 ID 的产生方式后这里提出来一种 虚拟 ID 的概念,即组合各种 ID 的生成的唯一 ID。

/**
 * 返回 唯一的虚拟 ID
 * @return ID
 */
public static String getUniquePsuedoID() {
    String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);

    // API >= 9 的设备才有 android.os.Build.SERIAL
    // http://developer.android.com/reference/android/os/Build.html#SERIAL
    // 如果用户更新了系统或 root 了他们的设备,该 API 将会产生重复记录
    String serial = null;
    try {
        serial = android.os.Build.class.getField("SERIAL").get(null).toString();
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    } catch (Exception exception) {
        serial = "serial";
    }

    // 最后,组合上述值并生成 UUID 作为唯一 ID
    return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}

高票答案5

Google I/O 有一年的演讲中提到了使用 UUID 并同步到云端的方案。如果您的项目中对有云端配置备份策略可以考虑使用下面的方法。

 

private static String uniqueID = null;
private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";

public synchronized static String id(Context context) {
    if (uniqueID == null) {
        SharedPreferences sharedPrefs = context.getSharedPreferences(
                PREF_UNIQUE_ID, Context.MODE_PRIVATE);
        uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
        if (uniqueID == null) {
            uniqueID = UUID.randomUUID().toString();
            Editor editor = sharedPrefs.edit();
            editor.putString(PREF_UNIQUE_ID, uniqueID);
            editor.commit();
        }
    }
    return uniqueID;
}

 

posted @ 2016-12-20 14:50  weidingqiang  阅读(814)  评论(0)    收藏  举报