Very often we need to detect if the user is opening the app for the first time, initializing some data, or opening the boot interface, and so on.
/* Method One: * First open when get Isfirstin value, default value is False * get false, prove not first open * get true, prove to be first opened; then set isfirstin value to False * */ Sharedpreferences sp = getsharedpreferences ("Isfirstin", activity.mode_private); Boolean isfirstin = Sp.getboolean ("isFirstInWith1.4", true); if (isfirstin) { Sharedpreferences.editor Editor = Sp.edit (); Editor.putboolean ("isFirstInWith1.4", false); Editor.commit (); New Alertdialog.builder (this). Setmessage ("This is the first time to open"). Show (); else { new Alertdialog.builder (this). Setmessage ("You have opened n times"). Show ();
Note: Since the user installs the new version number, we want to also display the first open, but the version number updates will retain the previous version number of the data, so the detection is open before.
So we add the version number to the key checked by each version number, like the isFirstInWith1.4 above, where 1.4 is the version number.
/* Method Two: * Check if there is a file at first open (com.example.test.isFirstIn) * Assuming already exists, prove not first open * does not exist, proves to be open for the first time; Create file after opening * */file dir = getfilesdi R ();// /data/data/com.example.test/filesfile f = new File (dir, "com.example.test.isFirstIn"); LOG.E ("Miquan", F.getabsolutepath ()), if (F.exists ()) {//dosomethingnew Alertdialog.builder (this). Setmessage (" You have opened N times "). Show (); else {try {f.createnewfile ();} catch (IOException e) {e.printstacktrace ();} Dosomethingnew Alertdialog.builder (this). Setmessage ("This is the first time to open"). Show ();
Detects if the user is opening the app for the first time