How to Execute Something Just Once Per Application Start

How can I execute something just once per application start?

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.

Run code ONCE on startup

In your main activity, declare a static boolean flag that you set to true when you run the start-up code. In onCreate, run the start-up code only if the flag is false. In onDestroy (or in any of the shut-down lifecycle methods, for that matter), clear the flag if the activity is finishing:

protected void onDestroy() {
super.onDestroy();
if (isFinishing()) {
startedFlag = false;
}
}

This will clear the flag when the activity is finishing but leave it untouched if the activity is being destroyed because of a configuration change.

There's still a catch: the activity's process might be killed off while paused and the app is in the background. In that case, the flag will be false when the activity is recreated by the system when the user tries to bring the app back to the foreground. If this is a problem, then you are going to have to make the flag persistent. I'd recommend using shared preferences for that.

Run a piece of code only once when an application is installed

Before all you can use SQLiteOpenHelper. It is preferred way to do things with database. This class have a onCreate(SQLiteDatabase) method, that called when first creating database. I think it suits you well.

If you want more flexibility and your first time logic is not tied only with database, you can use sample provided earlier. You just need to put it in startup spot.

There are 2 startup spots. If you have only single activity, you can put your code in onCreate method, so it will be like this:

public void onCreate(Bundle savedInstanceState) {
// don't forget to call super method.
super.onCreate(savedInstanceState);

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
// <---- run your one time code here
databaseSetup();

// mark first time has ran.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
}

Don't forget to put activity declaration in manifest, as well as it's intentfilters (action = MAIN, category = LAUNCHER).

If you have more than one activity and you don't want to duplicate your startup logic you can just put your initialization logic in Application instance, that is created before all activities (and other components, such as services, broadcast recievers, content providers).

Just create class like that:

public class App extends Application {

@Override
public void onCreate() {
super.onCreate();

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
// <---- run your one time code here
databaseSetup();

// mark first time has ran.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
}

All you need for this to work, is put in application tag in AndroidManifest.xml attribute android:name=".App".

<!-- other xml stuff -->

<application ... android:name=".App">

<!-- yet another stuff like nextline -->
<activity ... />
</application>

Run code only once after an application is installed on Android device

  1. Check if boolean X is True in shared preferences
  2. If not:

    a. Run the special code

    b. Save x as true in shared preferences

For example:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false)) {
// run your one time code
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}

Call something once in app lifecycle?

You can add it to onCreate() and only call the method if it hasn't been initialized/called previously.

protected void onCreate(Bundle b) {
if(shouldCall()) { // I know if the method has been called before
callMethodJustOnce();
}
}

If you are looking to call this method only once ever, I would take a look at most answers in here recommending using Preferences. But if you are talking about once per time the app is brought to life, this should be achieved in onCreate(), as this should only be called once the app is initialized and started.

How to launch activity only once when app is opened for first time?

What I've generally done is add a check for a specific shared preference in the Main Activity : if that shared preference is missing then launch the single-run Activity, otherwise continue with the main activity . When you launch the single run Activity create the shared preference so it gets skipped next time.

EDIT : In my onResume for the default Activity I do this:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
if(!previouslyStarted) {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
edit.commit();
showHelp();
}

Basically I load the default shared preferences and look for the previously_started boolean preference. If it hasn't been set I set it and then launch the help file. I use this to automatically show the help the first time the app is installed.

Run specific code only once per session on App Start in Unity

Simple answer is to have a singleton. Which is made when your game starts, runs the code, and basically because its never destroyed that start code never runs again.

Your code you had is almost all of it

public class RunCodeOnce : MonoBehaviour
{
public static RunCodeOnce Instance;

void Awake()
{
if (Instance!=null) { Destroy(gameObject); return; } // stops dups running
DontDestroyOnLoad(gameObject); // keep me forever
Instance = this; // set the reference to it

... code to run only once ...
}
}

this makes an object which persists, which no matter what will never allow a duplicate of itself and because it wont die no matter how much you load new scenes or whatever, unless you physically destroy it yourself in code, it wont die it will be there the whole session.

How do I execute a method only once in Android?

You can do this, by using shared preferences. Store a value in shared preferences:

SharedPreferences prefs  = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("key",1); //or you can also use editor.putString("key","value");
editor.commit();

After doing so, say for example if user recalls an activity, then you check the value of in the shared prefs and if it is found, then just perform the action you wish to do else, allow the user to continue with the activity.

To retrieve values from a shared preferences file, call methods such as getBoolean() and getString(), providing the key for the value you want, and optionally a default value to return if the key isn't present.

Here is a quick reference:

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

Running code after Spring Boot starts

Try:

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {

@SuppressWarnings("resource")
public static void main(final String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);

context.getBean(Table.class).fillWithTestdata(); // <-- here
}
}

Function in JavaScript that can be called only once

If by "won't be executed" you mean "will do nothing when called more than once", you can create a closure:

var something = (function() {
var executed = false;
return function() {
if (!executed) {
executed = true;
// do something
}
};
})();

something(); // "do something" happens
something(); // nothing happens

In answer to a comment by @Vladloffe (now deleted): With a global variable, other code could reset the value of the "executed" flag (whatever name you pick for it). With a closure, other code has no way to do that, either accidentally or deliberately.

As other answers here point out, several libraries (such as Underscore and Ramda) have a little utility function (typically named once()[*]) that accepts a function as an argument and returns another function that calls the supplied function exactly once, regardless of how many times the returned function is called. The returned function also caches the value first returned by the supplied function and returns that on subsequent calls.

However, if you aren't using such a third-party library, but still want a utility function (rather than the nonce solution I offered above), it's easy enough to implement. The nicest version I've seen is this one posted by David Walsh:

function once(fn, context) { 
var result;
return function() {
if (fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}

I would be inclined to change fn = null; to fn = context = null;. There's no reason for the closure to maintain a reference to context once fn has been called.

Usage:

function something() { /* do something */ }
var one_something = once(something);

one_something(); // "do something" happens
one_something(); // nothing happens

[*] Be aware, though, that other libraries, such as this Drupal extension to jQuery, may have a function named once() that does something quite different.



Related Topics



Leave a reply



Submit