How can I execute something just once per application start?

前端 未结 10 1350
感情败类
感情败类 2020-11-28 06:45

I\'d like to implement an update checker in an application, and I obviously only need this to show up once when you start the application. If I do the call in the onCr

相关标签:
10条回答
  • 2020-11-28 07:06

    SharedPreferences seems like ugly solution to me. It's much more neat when you use application constructor for such purposes.

    All you need is to use your own Application class, not default one.

    public class MyApp extends Application {
    
        public MyApp() {
            // this method fires only once per application start. 
            // getApplicationContext returns null here
    
            Log.i("main", "Constructor fired");
        }
    
        @Override
        public void onCreate() {
            super.onCreate();    
    
            // this method fires once as well as constructor 
            // but also application has context here
    
            Log.i("main", "onCreate fired"); 
        }
    }
    

    Then you should register this class as your application class inside AndroidManifest.xml

    <application android:label="@string/app_name" android:name=".MyApp"> <------- here
        <activity android:name="MyActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
    

    You even can press Back button, so application go to background, and will not waste your processor resources, only memory resource, and then you can launch it again and constructor still not fire since application was not finished yet.

    You can clear memory in Task Manager, so all applications will be closed and then relaunch your application to make sure that your initialization code fire again.

    0 讨论(0)
  • 2020-11-28 07:09

    looks like you might have to do something like this

    PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
    
          int currentVersion = info.versionCode;
          this.versionName = info.versionName;
          SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
          int lastVersion = prefs.getInt("version_code", 0);
          if (currentVersion > lastVersion) {
            prefs.edit().putInt("version_code", currentVersion).commit();
           //  do the activity that u would like to do once here.
       }
    

    You can do this every time, to check if the app has been upgraded, so it runs only once for app upgrade

    0 讨论(0)
  • 2020-11-28 07:09

    This continues on @Vitalii's answer.

    After having setup the Application class, if access to the Activity is required, we can use the aptly named android library "Once" https://github.com/jonfinerty/Once.

    In the Application class's onCreate method

    Once.initialise(this)
    

    In the Activity / Fragment class's onCreate / onViewCreated method.

    val helloTag = "hello"
    if (!Once.beenDone(Once.THIS_APP_SESSION, helloTag)) {
        //Do something that needs to be done only once
        Once.markDone(helloTag) //Mark it done
    }
    
    0 讨论(0)
  • 2020-11-28 07:11

    Use SharedPreference for this-

    1. If you are not restarting your launcher activity again once your app is active then in that case you case use it.

    2. Use this in a Splash screen if you are implementing it in the app.

    3. If you are not using any splash screen then you need to create a activity with no view set and on it's oncreate call you can do start updation and start your main activity.

    you can use counter value or boolean for this.

    Here is SharedPreference doc:

    http://developer.android.com/reference/android/content/SharedPreferences.html

    0 讨论(0)
  • 2020-11-28 07:18

    I do this the same way as described in the other answer. I just have a global variable in the first activity which matches the release number from the manifest. I increment it for every upgrade and when the check sees a higher number, it executes the one-time code.

    If successful, it writes the new number to shared preferences so it wont do it again until the next upgrade.

    Make sure you assign the default to -1 when you retrieve the version from shared preferences so that you error on the side of running the code again as opposed to not running it and not having your app update correctly.

    0 讨论(0)
  • 2020-11-28 07:18
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
      if (!prefs.getBoolean("onlyonce", false)) {
        // <---- run your one time code here
    
    
        // mark once runned.
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean("onlyonce", true);
        editor.commit();
      }
    }
    
    0 讨论(0)
提交回复
热议问题