MobileAppDeveloper
MobileAppDeveloper

Reputation: 1049

Unique Id for my android app

I want to create a unique ID for my android app so that my server can identify from which device the request has come and send messages to the app accordingly. I read that ANDROID_ID is not safe to use as a unique identifier as it can be compromised on a rooted device. And also some manufacturer don't even provide it.

Is UUID safe to use for my porpose ? Is it really the globally unique id for the app ? If yes, I am planning to store it using the keystore so that I can keep it until the app uninstalls. Is it the right approach. Please suggest.

Upvotes: 3

Views: 3400

Answers (1)

Big Zak
Big Zak

Reputation: 1100

Its actually safe to use UUID, this is a helper function I created to get the UUID myself,keep it in Helper.java , so you will call it :

Helper.getDeviceId(context); 

also don forget the change String sharedPrefDbName variable to your sharef db name, also you can store the UUID in DB or local file incase app is uninstalled like you said.

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

Upvotes: 2

Related Questions