onCreate method keeps getting called when the orie

2019-07-24 10:01发布

问题:

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"