简体   繁体   中英

Android activity OnCreate is called twice

I start my second activity like this:

Intent intentNotAuthorized = new Intent(SplashScreen.this, NotAthorized.class);
            intentNotAuthorized.putExtra("message","dummy");
            intentNotAuthorized.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intentNotAuthorized);
            finish();

When go back back to the first activity using:

      Intent intentSplash = new Intent(NotAthorized.this, SplashScreen.class);
        intentSplash.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intentSplash);
        finish();

when the first activity is created Oncreate was called twise

The point is you should not create an intent when you want to back to the first activity.

the right way is just call finish() method in the second activity.

Option 1:

I have observed this issue when you are trying start an activity with values in the intent.

Below is an example where Activity_A calls Activity_B and passes values in the intent to be collected in Activity_B:

Intent intent = new Intent(this, activityB.class);
intent.putExtra("val1", someValue1);
intent.putExtra("val2", someValue2);
intent.putExtra("val3", someValue3);
this.StartActivity(intent);
finish();

Manifest File:

In this case, you can set the android:launchMode="singleInstance" or android:launchModel="singleTop" in your AndroidManifest.xml and Activity_B will only launch once. Hope this helps.

Option 2:

I think Nathaniel is giving you good advice to move your camera intent launching into onResume.

However, you'll need to differentiate between an onResume that is your activity starting for the first time from one that is happening because of your activity resuming after the camera intent is finished. If you dont, you'll get the loop you see.

To do this, you can alter your onActivityResult() to set a member variable in your Activity called something like isResumingFromCaptureIntent. Set it to true in onActivityResult when the resultCode matches what you used to start the camera intent. Then, in your onResume, check isResumingFromCaptureIntent, if true you know you dont need to start the camera intent and can set is back to false and proceed with whatever else your activity needs to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM