当设备方向改变时 onCreate 方法不断被调用
我有一个 AsyncTask
,它在我的 Main Activity
中被调用 onCreate()
。在同一个 Activity 中,如果方向发生变化,AsyncTask 会再次被调用。如何防止这种情况发生,或者如何重组我的程序以避免这种情况发生?
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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您应该检查 处理运行时更改
您可以使用
在配置更改期间保留对象
允许您的 Activity 在配置更改时重新启动,但将有状态对象携带到 Activity 的新实例。
处理配置改变自己
防止系统在某些配置更改期间重新启动您的 Activity,但在配置发生更改时接收回调,以便您可以根据需要手动更新您的 Activity。
要在运行时配置更改期间保留对象:
重写onRetainNonConfigurationInstance() 方法以返回您想要保留的对象。
当您的 Activity 再次创建时,调用 getLastNonConfigurationInstance() 来恢复您的对象。
保留在OnCreate中;
或者只需将此代码添加到您的活动清单中
或
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.
Retain in OnCreate ;
Or simply add this code in you Manifest of you Activity
or