Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

android - How do I avoid onCreate() being called when starting an Activity?

I want to reload an activity from stack.

I use startActivity() to start new activities. When I'm on Activity D I want to reload Activity A and not start a new Intent. I can't use startActivity() when calling A from D because it will fire onCreate() which starts a thread to fetch some data.

EDIT: Updated the stack.

If I use FLAG_ACTIVITY_REORDER_TO_FRONT it calls the onCreate() method again.

Following is my scenario.

Login Activity ?→ Activity A → Activity B → Activity C → Activity D → Activity A

How do I avoid onCreate() being called?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to take a totally different approach. It doesn't matter if you start your Activity with startActivity() or startActivityForResult() because onCreate(), onStart() and onResume() will be called when you start an Activity.

Now if you have a method in your Activity class that starts another thread to do some work then you have to work with flags. If your Activity requires to automatically start the thread on first execution then you have to wrap it around an if clause to check for a flag you set when it is first run.

The idea is to have your Activity set a boolean to true in either your Application instance or SharedPreferences when the thread is first executed. When you come back to that Activity and don't want that thread to be run automatically due to onCreate() being called then you have to wrap your calling code around some if clause like in the example below.

Here is an example.

@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    // Other stuff

    if (!YourApplicationInstance.wasCalled) {
        // Run your thread or do something else you want to do only once.

        // Set the wasCalled flag to true to not run this code again
        // if onCreate() is called a second time.
        YourApplicationInstance.wasCalled = true;
    }
}

You'll have to read Using Application context everywhere? to understand how to implement my pseudo class YourApplicationInstance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...