Is it normal for the “activity.onCreate()” method

2019-01-18 11:04发布

问题:

I have some code in the onCreate method an Activity and noticed that it is being called three times. Is it normal behaviour? Thanks.

回答1:

You might want to read through the documentation on the Activity lifecycle.

OnCreate will only be called one time for each lifetime of the Activity. However, there are a number of situations that can cause your activity to be killed and brought back to life. Thus, onCreate will be called again.

To support this properly, you can save state information in onSaveInstanceState and restore it fron the state bundle you get in on create.



回答2:

Other than the expected cases, I have observed that only those activities (onCreate) are called twice which are creating new Thread or Runnable. (I believe this to be a bug in Android).

The solution is simple (though you may not like it :p)

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_screen);

        if(savedInstanceState == null){
            // everything else that doesn't update UI
        }
    }


回答3:

You can also handle the configuration changes on your own, setting on the AndroidManifest the following statement, in the activity configuration:

android:configChanges="orientation|keyboardHidden"

For further information, you can have a look at the official documentation



回答4:

The below is a scenario I encountered (and solved) which produces the behavior you are describing:

There are 3 events that will trigger OnTouch - 1. android.view.MotionEvent.ACTION_UP 2. android.view.MotionEvent.ACTION_DOWN 3. android.view.MotionEvent.ACTION_MOVE.

Often, all three of these events fire at the same time to trigger the OnTouch listener. When this listener is used to launch an activity (via an Intent passed to startActivity()), you can reproduce this behavior which would call OnCreate on the Activity multiple times (3 in this example).

If it's not this listener type you are using to start the activity, you may want to look into the documentation for whatever listener is triggering your activity to see if you are experiencing a similar scenario. Chances are that not just one event triggers the listener.



回答5:

I had a similar problem, it was caused by MobileAds. After I initialized them BEFORE super.onCreate(...) the problem was gone.