Peter Lo Peter Lo - 1 month ago 12
Android Question

Android: avoid calling onCreate() when back from another activity

Assume my application contains two activity, A and B.
Both are limited to portrait in AndroidManifest.

Activity A started Activity B.
In Activity B, there is a button, which calls

finish()
when clicked.

The problem is...
When I hold the device vertically(portrait) and click the button, the calling sequence is

B.onStop();
B.onDestory();
A.onStart();


However, when I hold the device horizontally(landscape), the sequence becomes

B.onStop();
B.onDestory();
A.onCreate();
A.onStart();


I do NOT want the
A.onCreate()
!!!

I tried pressing the
Back
button.
A.onCreate()
is not called.
So... simulating the
Back
button is somehow the solution

I have tried the followings, all of them called
A.onCreate()
..

finish();


.

onBackPressed()


.

dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));


EDITED

I have to say again.
Both activities are limited to portrait in AndroidManifest.
onConfigurationChanged
is never called.

Static variable is not accepted. Since this will cause other problem..

Answer

It happens because you have changed the orientation at some stage when the application has started, imo.
On orientation change the activity is destroyed then recreated. To avoid it handle the orientation.

Handle the orientation change by yourself by adding the following line in the manifest file , under activity.

<activity android:name=".Activity_name"
android:configChanges="orientation|keyboardHidden|screenSize"
Comments