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

霸气de小男生 提交于 2019-12-11 00:40:16

问题


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..


回答1:


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"



回答2:


If you want not to call some code in onCreate when the orientation changes you can do as follows:

in your activity override onRetainLastNonConfigurationInstance() and make it return Boolean.TRUE.

In your onCreate check Boolean.TRUE.equals(getLastNonConfigurationInstance()) and, if yes, this means your onCreate has been called because (and only becase) the orientation has been changed.




回答3:


in your condition,Set

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

can avoid Activity reCreate new instance,but some device will cause black screen and onCreate will still be called , if you want to prevent this condition,you can override onConfigurationChanged() method,and do this:

@Override
protected void onConfigurationChanged(Configuration newConfig) {
    newConfig.orientation = Configuration.ORIENTATION_PORTRAIT;
    super.onConfigurationChanged(newConfig);
}


来源:https://stackoverflow.com/questions/16434269/android-avoid-calling-oncreate-when-back-from-another-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!