1. 程式人生 > >通過androidId和系統引數生成手機唯一標識

通過androidId和系統引數生成手機唯一標識

/**
     * 獲取儲存的uuid,未儲存時候重新生成
     * @param context
     * @return
     */
    public static String getDeviceUUID(Context context) {
        String uuid = loadDeviceUUID(context);
        if (TextUtils.isEmpty(uuid)) {
            uuid = createDeviceUUID(context);
            saveDeviceUUID(context, uuid);
        }
        return uuid;
    }

    /**
     * 生成uuid
     *
     * @param context
     * @return
     */
    public static String createDeviceUUID(Context context) {
        String androidId = getAndroidId(context);
//        androidId = "9774d56d682e549c";
        //有些手機系統存在bug,androidId被寫死為9774d56d682e549c,小概率事件可以忽略
//        if ("9774d56d682e549c".equals(androidId)) {
        //生成隨機androidId,app解除安裝會丟失
//            Random random = new Random();
//            androidId = Integer.toHexString(random.nextInt()) + Integer.toHexString(random.nextInt()) + Integer.toHexString(random.nextInt());
//        }
        return new UUID(androidId.hashCode(), getPhoneInfo().hashCode()).toString();
    }

    public static String getPhoneInfo() {
        //選取一些系統不變引數參與計算uuid
        StringBuffer buildSB = new StringBuffer();
        buildSB.append(Build.BRAND).append("/");
        buildSB.append(Build.PRODUCT).append("/");
        buildSB.append(Build.DEVICE).append("/");
        buildSB.append(Build.ID).append("/");
        buildSB.append(Build.VERSION.INCREMENTAL);
        return buildSB.toString();
    }

    private static void saveDeviceUUID(Context context, String uuid) {
        context.getSharedPreferences("config", Context.MODE_PRIVATE).edit().putString("uuid", uuid).apply();
    }

    private static String loadDeviceUUID(Context context) {
        return context.getSharedPreferences("config", Context.MODE_PRIVATE).getString("uuid", null);
    }

    public static String getAndroidId(Context context) {
        return Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }