Android:如何仅在安装App时调用方法

时间:2013-02-28 11:45:53

标签: android installation

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

但是我想在首次安装应用程序时只执行一次;因为之后我会自己处理文件的更新。

请问怎么办?

感谢您的任何建议

4 个答案:

答案 0 :(得分:5)

在app中只做一次你需要这样的东西:

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
}

答案 1 :(得分:3)

您可以使用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();
        }

答案 2 :(得分:1)

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

答案 3 :(得分:1)

你可以在你的主要活动onCreate方法中检查你的共享优先文件中是否有你选择名字的任何仲裁布尔值。在你的第一次启动时,这不会在那里,所以你可以调用你的方法并将你的布尔值设置为true。这意味着在您下次启动应用时,此值将为true,并且可以跳过对您的函数的调用。