Assigning a unique ID every time android app is opened

233 views Asked by At

I am creating an app whose main purpose is to collect data for experiments, which it uploads to a database at the end of each experiment. I want to assign a unique identifier each time the experiment is run (either opening the app, or restarting the experiment).

I cannot use an identifier that is unique to the device only, since there will be multiple experiments performed on each device.

I cannot use an identifier based on the time of the experiment (or some other form of sequential assignment), since it is possible for multiple devices to submit their data at the same time.

At the moment, my solution is to assign a random number each time an experiment is run, which is checked against a database and recalculated if it exists. This isn't perfect since it is possible, but rare, that two experiments will be run at the same time and assigned (by chance) the same identifier.

How can I assign a unique identifier each time the experiment is run?

3

There are 3 answers

0
Stephan Branczyk On BEST ANSWER

What you're doing is already correct.

That being said, if you really don't want to check the database every time you do an insert, you can always concatenate the unique MAC wifi Address of the device to a unique time stamp. Do not use the IMEI number (wifi-only tablets for instance do not have an IMEI number, and technically IMEI numbers can collide as well because of negligent manufacturers).

Are MAC wifi address unique? That's not guaranteed either, but if you concatenate it to a timestamp, it will improve the chances of not having a collision.

And if you want to further improve your chances, you could always concatenate the wifi MAC address, along with a time stamp, along with a UUID. Again, this strategy doesn't guarantee uniqueness either, but in my opinion it gets pretty close.

0
mbmc On

You can use a UUID. From the doc:

UUID is an immutable representation of a 128-bit universally unique identifier
0
Michael P On

There's virtually zero chance that 2 experiments will happen in the same time up to milliseconds, let alone nano seconds which you can get from the system. So you can easily rely on their uniqueness. If that makes you uncomfortable, concatenate the device id with the time in nano seconds to the experiment, which will make it even less likely to collide. If you want to go absolutely crazy. Build a server that will have a hashmap of all the numbers that it already generated, and will regenerate a new one for every experiment app instance. I an give you an algorithm to make it efficient if you want.

You can also use GUID https://www.guidgenerator.com/ which is basically an equivalent of randomly picking a number between 0 to 2^128-1, which is a LOT.