简体   繁体   English

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

[英]Android: how to call method only on installation of App

I need to call a method (or start an activity, or something else) that will update a file containing data the app needs. 我需要调用一个方法(或启动一个活动,或其他东西)来更新包含应用所需数据的文件。

But I want it to be done only once, when the app is first installed; 但是我希望它首次安装应用程序时只执行一次; because after I will handle the update of the file myself. 因为之后我会自己处理文件的更新。

Please how can it be done? 请问怎么做?

Thanks for any suggestion 谢谢你的任何建议

to do something only once in app you need something like this : 在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
}

You can do it by using SharedPrefrences . 您可以使用SharedPrefrences Look this: 看看这个:

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();
        }

Create a launcher activity that loads when your app starts. 创建一个启动应用程序启动时加载的启动器活动。 Have it check for a value (such as firstStartUp) in SharedPreferences ( http://developer.android.com/guide/topics/data/data-storage.html#pref ) . 让它检查SharedPreferences中的值(例如firstStartUp)( http://developer.android.com/guide/topics/data/data-storage.html#pref )。 The first time you ever run the app this value will not exist and you can update your data. 第一次运行应用程序时,此值将不存在,您可以更新数据。 After your data is updated set the value in shared preferences so that your app finds it the next time it launches and will not attempt to update the data again. 更新数据后,在共享首选项中设置值,以便您的应用程序在下次启动时找到它,并且不会再次尝试更新数据。

You could do it by, in your main activities onCreate method, checking your shared prefereces file for any arbitary boolean that you pick the name of. 你可以在你的主要活动onCreate方法中检查你的共享首选项文件中是否有你选择名称的任何仲裁布尔值。 On your first launch this won't be there so you can then call your method and set your boolean to true. 在你的第一次启动时,这不会在那里,所以你可以调用你的方法并将你的布尔值设置为true。 This means on the next start of your app this value would be true and the call to your function can be skipped. 这意味着在您的应用程序的下一次启动时,此值将为true,并且可以跳过对函数的调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM