1

How to make sure Activity window get initialized only once in Android application. I was asked this question once and I am not sure what the answer is. But it seems like we can do it in onCreate() method.

public class YourActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState == null) {
            // Initialized here once
        }
    }
}

Is this the right way of doing it or is there any other way we can achieve this?

3
  • 1
    It's a bit unclear what you are looking to do. The snippet you posted will work such that the code inside your if statement will only be called when the Activity is initialized for the first time, and not on any subsequent calls to onCreate() (such as due to a configuration change like device rotation). If that's not what you are needing, please clarify further. Cheers.
    – devunwired
    Nov 1, 2011 at 21:09
  • 1
    I want to initialize some member variable in this if block and want to make sure that these should get called only once. Is there any other scenario in which this if block will get executed except very first time. I guess similar kind of work can be done using android:launchMode flags.
    – Rakesh
    Nov 1, 2011 at 22:18
  • Welcome to Stackoverflow! If you find a response is helpful, please up vote it. If the response successfully answers your question, please click the green check mark next to it to accept the answer. Also please look at stackoverflow.com/questions/how-to-ask for advice on how to write a good question Nov 2, 2011 at 4:32

1 Answer 1

2

Use singleTop for the launch mode for the Activity.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.