Created
December 3, 2012 03:08
-
-
Save ktuite/4192379 to your computer and use it in GitHub Desktop.
Generating and storing a random, unique user id to track unique installations of an android app.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// adaptation of: http://android-developers.blogspot.com/2011/03/identifying-app-installations.html | |
// but using shared preferences instead of a file: http://developer.android.com/reference/android/content/SharedPreferences.html | |
// here's a better look at using shared preferences: http://developer.android.com/guide/topics/data/data-storage.html#pref | |
public class UniqueId { | |
private static String sID = null; | |
private static final String SHARED_PREF_KEY = "SKETCHABIT2"; | |
private static final String ID_KEY = "id"; | |
public synchronized static String id(Context context) { | |
if (sID == null) { | |
SharedPreferences pref = context.getSharedPreferences( | |
SHARED_PREF_KEY, 0); | |
sID = pref.getString(ID_KEY, ""); | |
if (sID == "") { | |
sID = generateAndStoreUserId(pref); | |
} | |
} | |
return sID; | |
} | |
private synchronized static String generateAndStoreUserId(SharedPreferences pref) { | |
String id = UUID.randomUUID().toString(); | |
SharedPreferences.Editor editor = pref.edit(); | |
editor.putString(ID_KEY, id); | |
editor.commit(); | |
return id; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment