2017-04-14 73 views
2

我想爲我的android應用程序創建一個唯一的ID,以便我的服務器可以識別請求來自哪個設備並相應地嚮應用程序發送消息。我讀到ANDROID_ID作爲唯一標識符使用並不安全,因爲它可能會在根設備上受到威脅。而且一些製造商甚至不提供它。我的android應用程序的唯一ID

UUID是否可以安全地用於我的文檔?它真的是應用程序的全球唯一ID嗎?如果是,我打算使用密鑰庫存儲它,以便我可以保留它,直到應用程序卸載。這是正確的做法嗎?請建議。

+0

https://developer.android.com/training/articles/user-data-ids.html「我打算使用密鑰存儲來存儲它,以便我可以保留它直到應用程序卸載」 - 我希望只要應用程序的內部存儲空間被清除,應用程序的密鑰庫條目就會被刪除,所以我不確定這對您是否有好處。 – CommonsWare

+0

https://developer.android.com/training/articles/user-data-ids.html唯一ID也涉及隱私問題,所以請完整閱讀此文檔 –

+0

只要安裝了我的應用程序,我想保留此ID 。在卸載它確定重置它。感謝有關ID的好文章。他們討論使用實例ID或UUID來達到我的目的。可以使用它們中的任何一個嗎?另一個已知的優點/缺點?請建議。 – MobileAppDeveloper

回答

0

它實際上安全使用UUID,這是我創建拿到UUID自己,保持它在Helper.java,所以你會稱它爲一個輔助功能:

Helper.getDeviceId(context); 

也不要忘記了改變字符串sharedPrefDbName變量到您的sharef db名稱,您也可以將UUID存儲在數據庫或本地文件中incase應用程序像您所說的那樣被卸載。

//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 
+0

感謝您的回覆。我正在閱讀我們可以使用的不同類型的ID。對於我的目的,實例ID或UUID很有用。但是哪一個更好,如果是這樣的話? – MobileAppDeveloper

+0

經過一番研究,我選擇了UUID ..這是來自android dev(https://developer.android.com/training/articles/user-data-ids.html#version_specific_details_identifiers_in_m)的引用:「#3:Use an Instance ID或一個私人存儲的GUID,除了支付欺詐預防和電話以外的所有其他用例。對於絕大多數非廣告用例,實例ID或GUID應該足夠。「,在我的情況下,UUID是完美的,因爲我需要跟蹤用戶的存在和設備的變化,我同步本地UUID到我的遠程服務器,所以每x秒應用程序確認如果.. – razzbee

+0

..他們匹配,如果他們不需要,新的短信驗證是必需的在新設備上對用戶進行身份驗證,然後重新生成新的UUID並重新連接到我的服務器。這有助於防止多個設備使用同一個帳戶,我從whatsapp獲得了靈感。 – razzbee