Roland
Roland

Reputation: 876

How to know if my activity was open by Android?

I want to run some function only when my app is first open. When the activity is cose and return it, the functions are runiing againg. I want only to run one time, when thr app is open.

The problem is: When I run my app and this first activity is open. Then I left this activity to another with a intent and the finish() method. When i return to this first activity, the code run again. I dont want this code run again, only time I open the app.

Upvotes: 0

Views: 166

Answers (4)

FunkTheMonk
FunkTheMonk

Reputation: 10938

It sounds like you want a static variable.

Whilst the process running your app is alive the static variable will be kept. If the VM dies, the state of the static is lost.

Since there isn't any guarantee of when or even if the VM will be destroyed by the system whilst your activity is in the background, it isn't fool proof, but might be ok for what you're trying to do.

Upvotes: 1

David Wasser
David Wasser

Reputation: 95636

Your question is a bit confusing, since you state that you want code to run only once, but in another answer that suggested using SharedPreferences for this, you wrote in a comment

I dont want to run it only once. I want it run every time the app is open

If you put code in onCreate() of your starting (root) activity, that code will run each time the Activity is started. If you put code in onResume(), then the code will run each time your activity is started, or brought to the foreground.

Upvotes: 0

Yjay
Yjay

Reputation: 2737

A great way to run something only once is by saving a boolean flag in SharedPreferences.

(in your Activity)

public static final String PREFS_FILE = "prefs";
public static final String FIRST_OPEN_PREF = "firstopen";

...

SharedPreferences settings = getSharedPreferences(PREFS_FILE, MODE_PRIVATE);
boolean activityWasOpenBefore = settings.getBoolean(FIRST_OPEN_PREF, false);

if(activityWasOpenBefore) {
    //Do something if my activity was open before
} else {
    //Do something if this is the first time the activity is open

    SharedPreferences.Editor editor = settings.edit();
    editor.putBoolean(FIRST_OPEN_PREF, true);
    editor.commit();
}

http://developer.android.com/guide/topics/data/data-storage.html#pref

Upvotes: 2

Daniel M.
Daniel M.

Reputation: 486

You should create a class that uses SharedPrefences .

When the app is first created save a value into SharedPreferences that states that.

Any other time your app opens simply check whether or not the value is present in SharedPreferences.

Upvotes: 1

Related Questions