簡體   English   中英

我的Android應用程序的唯一ID

[英]Unique Id for my android app

我想為我的android應用程序創建一個唯一的ID,以便我的服務器可以識別請求來自哪個設備,並相應地向該應用程序發送消息。 我讀到,ANDROID_ID不能用作唯一標識符,因為它可能在有根設備上遭到破壞。 而且有些制造商甚至沒有提供它。

UUID可安全用於我的用途嗎? 它真的是該應用程序的全球唯一ID嗎? 如果是,我計划使用密鑰庫存儲它,以便可以保留它直到應用程序卸載。 這是正確的方法。 請提出建議。

使用UUID實際上是安全的,這是我創建的一個幫助程序函數,用於自己獲取UUID,將其保留在Helper.java中,因此您將其稱為:

Helper.getDeviceId(context); 

也不要忘記將String sharedPrefDbName變量更改為您的sharef數據庫名稱,如果您像所說的那樣卸載了應用程序,也可以將UUID存儲在數據庫或本地文件中。

//uuid
static  String deviceId;

static String sharedPrefDbName = "MyAPPDB";

/**
 * getDeviceId
 * @param context
 * @return String
 */
public static String getDeviceId(Context context){

    //lets get device Id if not available, we create and save it
    //means device Id is created once

   //if the deviceId is not null, return it
    if(deviceId != null){
        return deviceId;
    }//end

    //shared preferences
    SharedPreferences sharedPref = context.getSharedPreferences(sharedPrefDbName,context.MODE_PRIVATE);

    //lets get the device Id
    deviceId = sharedPref.getString("device_id",null);

    //if the saved device Id is null, lets create it and save it

    if(deviceId == null) {

        //generate new device id
        deviceId = generateUniqueID();

        //Shared Preference editor
        SharedPreferences.Editor sharedPrefEditor = sharedPref.edit();

        //save the device id
        sharedPrefEditor.putString("device_id",deviceId);

        //commit it
        sharedPrefEditor.commit();
    }//end if device id was null

    //return
    return deviceId;
}//end get device Id


/**
 * generateUniqueID - Generate Device Id
 * @return
 */
public static String generateUniqueID() {

    String id = UUID.randomUUID().toString();

    return id;
}//end method

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM