I’m trying to implement the code found below so that I can generate a random ID number for the user right when the app is installed. I just have a couple questions.
- If I create a new file for this (Install.java) how do I access the ID in another class?
-
How do I make sure that this part of the program is executed when the app is first installed? Right now, the program starts on my Main.java class (I’m new to Java). Will it just run when the app is installed?
public class Install { private static String sID = null; private static final String INSTALLATION = "INSTALLATION"; public synchronized static String id(Context context) { if (sID == null) { File installation = new File(context.getFilesDir(), INSTALLATION); try { if (!installation.exists()) writeInstallationFile(installation); sID = readInstallationFile(installation); } catch (Exception e) { throw new RuntimeException(e); } } return sID; } private static String readInstallationFile(File installation) throws IOException { RandomAccessFile f = new RandomAccessFile(installation, "r"); byte[] bytes = new byte[(int) f.length()]; f.readFully(bytes); f.close(); return new String(bytes); } private static void writeInstallationFile(File installation) throws IOException { FileOutputStream out = new FileOutputStream(installation); String id = UUID.randomUUID().toString(); out.write(id.getBytes()); out.close(); } }
As far as I know you don’t get a way to run any arbitrary code right after installation is complete.
I think the closest you can get is make a check inside your MainActivity onCreate() method that determines whether or not this is the first run (a good way to check this might be to get a reference to your file and call file.exists(), the resulting boolean will tell you whether or not you need to create your UID file.