确定Android应用程序是否是第一次使用

我目前正在开发一个Android应用程序。 第一次启动应用程序时,我需要做一些事情,即代码只在第一次启动程序时运行。

另一个想法是使用共享首选项中的设置。 和检查一个空文件一样的一般想法,但是你没有空的文件,没有被用来存储任何东西

您可以使用SharedPreferences来确定是否是首次启动应用程序。 只需使用布尔variables (“my_first_time”),并在“第一次”任务结束时将其值更改为false

这是我第一次打开应用程序的代码:

final String PREFS_NAME = "MyPrefsFile"; SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); if (settings.getBoolean("my_first_time", true)) { //the app is being launched for first time, do something Log.d("Comments", "First time"); // first time task // record the fact that the app has been started at least once settings.edit().putBoolean("my_first_time", false).commit(); } 

我build议不仅存储布尔标志,而且还要存储完整的版本代码。 这样,您也可以在开始时查询它是否是新版本中的第一个开始。 例如,您可以使用此信息来显示“最新消息”对话框。

下面的代码应该可以从“是一个上下文”(activity,services,…)的任何android类中运行。 如果您希望将其放在单独的(POJO)类中,则可以考虑使用“静态上下文”,如此处所述。

 /** * Distinguishes different kinds of app starts: <li> * <ul> * First start ever ({@link #FIRST_TIME}) * </ul> * <ul> * First start in this version ({@link #FIRST_TIME_VERSION}) * </ul> * <ul> * Normal app start ({@link #NORMAL}) * </ul> * * @author schnatterer * */ public enum AppStart { FIRST_TIME, FIRST_TIME_VERSION, NORMAL; } /** * The app version code (not the version name!) that was used on the last * start of the app. */ private static final String LAST_APP_VERSION = "last_app_version"; /** * Finds out started for the first time (ever or in the current version).<br/> * <br/> * Note: This method is <b>not idempotent</b> only the first call will * determine the proper result. Any subsequent calls will only return * {@link AppStart#NORMAL} until the app is started again. So you might want * to consider caching the result! * * @return the type of app start */ public AppStart checkAppStart() { PackageInfo pInfo; SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); AppStart appStart = AppStart.NORMAL; try { pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); int lastVersionCode = sharedPreferences .getInt(LAST_APP_VERSION, -1); int currentVersionCode = pInfo.versionCode; appStart = checkAppStart(currentVersionCode, lastVersionCode); // Update version in preferences sharedPreferences.edit() .putInt(LAST_APP_VERSION, currentVersionCode).commit(); } catch (NameNotFoundException e) { Log.w(Constants.LOG, "Unable to determine current app version from pacakge manager. Defenisvely assuming normal app start."); } return appStart; } public AppStart checkAppStart(int currentVersionCode, int lastVersionCode) { if (lastVersionCode == -1) { return AppStart.FIRST_TIME; } else if (lastVersionCode < currentVersionCode) { return AppStart.FIRST_TIME_VERSION; } else if (lastVersionCode > currentVersionCode) { Log.w(Constants.LOG, "Current version code (" + currentVersionCode + ") is less then the one recognized on last startup (" + lastVersionCode + "). Defenisvely assuming normal app start."); return AppStart.NORMAL; } else { return AppStart.NORMAL; } } 

它可以从这样的活动中使用:

 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); switch (checkAppStart()) { case NORMAL: // We don't want to get on the user's nerves break; case FIRST_TIME_VERSION: // TODO show what's new break; case FIRST_TIME: // TODO show a tutorial break; default: break; } // ... } // ... } 

基本逻辑可以使用这个JUnittesting来validation:

 public void testCheckAppStart() { // First start int oldVersion = -1; int newVersion = 1; assertEquals("Unexpected result", AppStart.FIRST_TIME, service.checkAppStart(newVersion, oldVersion)); // First start this version oldVersion = 1; newVersion = 2; assertEquals("Unexpected result", AppStart.FIRST_TIME_VERSION, service.checkAppStart(newVersion, oldVersion)); // Normal start oldVersion = 2; newVersion = 2; assertEquals("Unexpected result", AppStart.NORMAL, service.checkAppStart(newVersion, oldVersion)); } 

更多的努力,你也可以testingandroid相关的东西(PackageManager和SharedPreferences)。 有兴趣编写testing的人吗? 🙂

请注意,上述代码只有在AndroidManifest.xml文件中没有涉及android:versionCode才能正常工作!

这里有一些代码 –

 String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/myapp/files/myfile.txt"; boolean exists = (new File(path)).exists(); if (!exists) { doSomething(); } else { doSomethingElse(); } 

你可以简单地检查是否存在一个空文件,如果它不存在,那么执行你的代码并创build文件。

例如

 if(File.Exists("emptyfile"){ //Your code here File.Create("emptyfile"); } 

我做了一个简单的类来检查你的代码是第一次运行/ N次!

创build一个独特的偏好

 FirstTimePreference prefFirstTime = new FirstTimePreference(getApplicationContext()); 

使用runTheFirstTime,select一个键来检查你的事件

 if (prefFirstTime.runTheFirstTime("myKey")) { Toast.makeText(this, "Test myKey & coutdown: " + prefFirstTime.getCountDown("myKey"), Toast.LENGTH_LONG).show(); } 

使用runTheFirstNTimes,select一个键并执行多less次

 if(prefFirstTime.runTheFirstNTimes("anotherKey" , 5)) { Toast.makeText(this, "ciccia Test coutdown: "+ prefFirstTime.getCountDown("anotherKey"), Toast.LENGTH_LONG).show(); } 
  • 使用getCountDown()更好地处理您的代码

FirstTimePreference.java

我解决了,以确定应用程序是否是你的第一次,取决于它是否是一个更新。

 private int appGetFirstTimeRun() { //Check if App Start First Time SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0); int appCurrentBuildVersion = BuildConfig.VERSION_CODE; int appLastBuildVersion = appPreferences.getInt("app_first_time", 0); //Log.d("appPreferences", "app_first_time = " + appLastBuildVersion); if (appLastBuildVersion == appCurrentBuildVersion ) { return 1; //ya has iniciado la appp alguna vez } else { appPreferences.edit().putInt("app_first_time", appCurrentBuildVersion).apply(); if (appLastBuildVersion == 0) { return 0; //es la primera vez } else { return 2; //es una versión nueva } } } 

计算结果:

  • 0:如果这是第一次。
  • 1:它已经开始了。
  • 2:它已经开始一次,但不是那个版本,即它是一个更新。

在支持库修订版本23.3.0(在v4中意味着可以回到Android 1.6的版本)中支持这一点。

在您的Launcher活动中,先打电话:

 AppLaunchChecker.onActivityCreate(activity); 

然后打电话:

 AppLaunchChecker.hasStartedFromLauncher(activity); 

如果这是该应用第一次启动,将会返回。

您可以使用Android SharedPreferences

Android SharedPreferences允许我们以键值对的forms存储私有的原始应用程序数据。

创build一个自定义类SharedPreference

  public class SharedPreference { android.content.SharedPreferences pref; android.content.SharedPreferences.Editor editor; Context _context; private static final String PREF_NAME = "testing"; // All Shared Preferences Keys Declare as #public public static final String KEY_SET_APP_RUN_FIRST_TIME = "KEY_SET_APP_RUN_FIRST_TIME"; public SharedPreference(Context context) // Constructor { this._context = context; pref = _context.getSharedPreferences(PREF_NAME, 0); editor = pref.edit(); } /* * Set Method Generally Store Data; * Get Method Generally Retrieve Data ; * */ public void setApp_runFirst(String App_runFirst) { editor.remove(KEY_SET_APP_RUN_FIRST_TIME); editor.putString(KEY_SET_APP_RUN_FIRST_TIME, App_runFirst); editor.commit(); } public String getApp_runFirst() { String App_runFirst= pref.getString(KEY_SET_APP_RUN_FIRST_TIME, "FIRST"); return App_runFirst; } } 

现在打开您的活动并初始化

  private SharedPreference sharedPreferenceObj; // Declare Global 

现在在OnCreate部分调用它

  sharedPreferenceObj=new SharedPreference(YourActivity.this); 

现在检查

 if(sharedPreferenceObj.getApp_runFirst().equals("FIRST")) { // That's mean First Time Launch // After your Work , SET Status NO sharedPreferenceObj.setApp_runFirst("NO"); } else { // App is not First Time Launch } 

为什么不使用数据库帮助器? 这将有一个很好的onCreate,这只是第一次启动应用程序。 这将有助于那些谁想要跟踪这个初始应用程序没有跟踪后安装。

我喜欢在我的共享首选项中有一个“更新计数”。 如果不存在(或默认的零值),那么这是我的应用程序的“第一次使用”。

 private static final int UPDATE_COUNT = 1; // Increment this on major change ... if (sp.getInt("updateCount", 0) == 0) { // first use } else if (sp.getInt("updateCount", 0) < UPDATE_COUNT) { // Pop up dialog telling user about new features } ... sp.edit().putInt("updateCount", UPDATE_COUNT); 

所以,现在,只要有一个用户应该知道的应用程序更新,我增加UPDATE_COUNT

  /** * @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); 

嗨,我正在做这样的事情。 它的作品对我来说

在共享首选项中创build一个布尔型字段。首次将其设置为false后,默认值为true {isFirstTime:true}。 在android系统中,没有什么比这更简单和可靠的了。