onCreate method keeps getting called when the orientation of device changes

假如想象 提交于 2019-12-11 01:06:31

问题


I have an AsyncTask which gets called onCreate() in my Main Activity. In the same Activity if the orientation changes the AsyncTask gets called again. How do I prevent this from happening or how do I restructure my program to avoid this happening?

public class Main extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pages);
        StartProcess sProcess = new StartProcess();
        sProcess.execute(this);
    }
}

回答1:


You can add android:configChanges="orientation" in the Activity manifest and manually set the contentView or change the layout by overriding the onConfigurationChanged method in your Activity.




回答2:


You should check Handling Run Time Changes

You can Handle either by using

Retain an object during a configuration change

Allow your activity to restart when a configuration changes, but carry a stateful Object to the new instance of your activity.

Handle the configuration change yourself

Prevent the system from restarting your activity during certain configuration changes, but receive a callback when the configurations do change, so that you can manually update your activity as necessary.

To retain an object during a runtime configuration change:

Override the onRetainNonConfigurationInstance() method to return the object you would like to retain.

When your activity is created again, call getLastNonConfigurationInstance() to recover your object.

@Override
public Object onRetainNonConfigurationInstance() {
    final MyDataObject data = collectMyLoadedData();
    return data;
}

Retain in OnCreate ;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final MyDataObject data = (MyDataObject) getLastNonConfigurationInstance();
    if (data == null) {
        data = loadMyData();
    }
    ...
}

Or simply add this code in you Manifest of you Activity

 android:screenOrientation="portrait" 

or

 android:screenOrientation="landscape" 


来源:https://stackoverflow.com/questions/8839736/oncreate-method-keeps-getting-called-when-the-orientation-of-device-changes

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