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?
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.