简体   繁体   中英

onCreate method keeps getting called when the orientation of device changes

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);
    }
}

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" 

您可以在Activity清单中添加android:configChanges="orientation" ,并通过覆盖Activity中的onConfigurationChanged方法来手动设置contentView或更改布局。

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