Determine if Android app is being used for the first time

前端 未结 16 1256
攒了一身酷
攒了一身酷 2020-11-22 12:47

I am currently developing an android app. I need to do something when the app is launched for the first time, i.e. the code only runs on the first time the program is launch

16条回答
  •  日久生厌
    2020-11-22 13:36

        /**
         * @author ALGO
         */
        import java.io.File;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.io.RandomAccessFile;
        import java.util.UUID;
    
        import android.content.Context;
    
        public class Util {
            // ===========================================================
            //
            // ===========================================================
    
            private static final String INSTALLATION = "INSTALLATION";
    
            public synchronized static boolean isFirstLaunch(Context context) {
                String sID = null;
                boolean launchFlag = false;
                if (sID == null) {
                    File installation = new File(context.getFilesDir(), INSTALLATION);
                    try {
                        if (!installation.exists()) {
    
                            writeInstallationFile(installation);
                        }
                        sID = readInstallationFile(installation);
    launchFlag = true;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
                return launchFlag;
            }
    
            private static String readInstallationFile(File installation) throws IOException {
                RandomAccessFile f = new RandomAccessFile(installation, "r");// read only mode
                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();
            }
        }
    
    > Usage (in class extending android.app.Activity)
    
    Util.isFirstLaunch(this);
    

提交回复
热议问题