【问题标题】:Android: how to call method only on installation of AppAndroid:如何仅在安装应用程序时调用方法
【发布时间】:2013-02-28 11:45:53
【问题描述】:

我需要调用一个方法(或启动一个活动,或其他)来更新包含应用所需数据的文件。

但我希望它只执行一次,即首次安装应用程序时;因为以后我会自己处理文件的更新。

请问怎么办?

感谢您的建议

【问题讨论】:

    标签: android installation


    【解决方案1】:

    要在应用程序中只做一次你需要这样的东西:

    boolean mboolean = false;
    
    SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
    mboolean = settings.getBoolean("FIRST_RUN", false);
    if (!mboolean) {
     // do the thing for the first time 
      settings = getSharedPreferences("PREFS_NAME", 0);
                        SharedPreferences.Editor editor = settings.edit();
                        editor.putBoolean("FIRST_RUN", true);
                        editor.commit();                    
    } else {
     // other time your app loads
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用 SharedPrefrences 来做到这一点。看这个:

      SharedPreferences ratePrefs = getSharedPreferences("First Update", 0);
              if (!ratePrefs.getBoolean("FrstTime", false)) {
      
              // Do update you want here
      
              Editor edit = ratePrefs.edit();
              edit.putBoolean("FrstTime", true);
              edit.commit();
              }
      

      【讨论】:

      • @pietmau 如果对您有帮助,请选择其中任何一个作为答案,以免出现未回答的问题..
      【解决方案3】:

      创建一个在您的应用启动时加载的启动器 Activity。让它检查 SharedPreferences (http://developer.android.com/guide/topics/data/data-storage.html#pref) 中的值(例如 firstStartUp)。第一次运行应用程序时,该值将不存在,您可以更新数据。更新数据后,在共享首选项中设置值,以便您的应用在下次启动时找到它,并且不会再次尝试更新数据。

      【讨论】:

        【解决方案4】:

        您可以通过在您的主要活动 onCreate 方法中检查您的共享首选项文件中是否有您选择的任意布尔值来做到这一点。在您第一次启动时,这将不存在,因此您可以调用您的方法并将您的布尔值设置为 true。这意味着在您的应用下一次启动时,此值将为 true,并且可以跳过对您的函数的调用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-23
          • 2015-03-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-08
          • 1970-01-01
          相关资源
          最近更新 更多