Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect the first time an Activity is opened on this session

I need to detect the first time an activity is called every time the user launches the app:

  • App is launched
  • Activity X is called for the first time
    • Do something
  • Activity Y, Z are called many times
  • Activity X is called again many times
    • Do nothing

... so "do something" has to be called only if the app was closed (or killed) and then be launched again.

like image 474
Demetrio Guilardi Avatar asked Sep 27 '13 04:09

Demetrio Guilardi


People also ask

How do I know if an app is running for the first time?

There's no reliable way to detect first run, as the shared preferences way is not always safe, the user can delete the shared preferences data from the settings! a better way is to use the answers here Is there a unique Android device ID? to get the device's unique ID and store it somewhere in your server, so whenever ...

How do you start an activity only once the app is opened for the first time?

It is important to check that the first activity which opens when the app is launched is MainActivity. java (The activity which we want to appear only once). For this, open the AndroidManifest. xml file and ensure that we have the intent-filter tag inside the activity tag that should appear just once.

What method is called when the activity is called for the first time?

in short onCreate is called first and when you comeback from an activity onResume will be called. onResume will also be called the first time as well.

Is first time launch in Android?

Android is developed by a consortium of developers known as the Open Handset Alliance and commercially sponsored by Google. It was unveiled in November 2007, with the first commercial Android device, the HTC Dream, being launched in September 2008.


1 Answers

I usually use static boolean variable inside the activity as a flag. Then, inside onCreate(), test the variable; if it's true, do something and flip the flag.

public class MainActivity extends Activity {
    private static boolean RUN_ONCE = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ...

        runOnce();
    }

    private void runOnce() {
        if (RUN_ONCE) {
            RUN_ONCE = false;

            // do something
        }
    }

    ...
}
like image 194
Andrew T. Avatar answered Sep 30 '22 17:09

Andrew T.