Using the Application Class
(使用应用程序类)
Depending on what you're doing in your initialization you could consider creating a new class that extends Application
and moving your initialization code into an overridden onCreate
method within that class.
(根据您在初始化过程中所执行的操作,可以考虑创建一个扩展Application
的新类,并将初始化代码移动到该类中重写的onCreate
方法中。)
public class MyApplicationClass extends Application {
@Override
public void onCreate() {
super.onCreate();
// TODO Put your application initialization code here.
}
}
The onCreate
in the application class is only called when the entire application is created, so the Activity restarts on orientation or keyboard visibility changes won't trigger it.
(仅在创建整个应用程序时才调用应用程序类中的onCreate
,因此Activity在方向上重新启动,否则键盘可见性更改不会触发它。)
It's good practice to expose the instance of this class as a singleton and exposing the application variables you're initializing using getters and setters.
(优良作法是将此类的实例公开为单例,并使用getter和setter公开要初始化的应用程序变量。)
NOTE: You'll need to specify the name of your new Application class in the manifest for it to be registered and used:
(注意:您需要在清单中指定新Application类的名称,以便注册和使用它:)
<application
android:name="com.you.yourapp.MyApplicationClass"
Reacting to Configuration Changes [UPDATE: this is deprecated since API 13;
(对配置更改做出反应 [更新:自API 13起不推荐使用;)
see the recommended alternative ] (请参阅推荐的替代方法 ])
As a further alternative, you can have your application listen for events that would cause a restart – like orientation and keyboard visibility changes – and handle them within your Activity.
(作为另一种选择,您可以让您的应用程序监听会导致重启的事件(例如方向和键盘可见性更改),并在Activity中处理它们。)
Start by adding the android:configChanges
node to your Activity's manifest node
(首先将android:configChanges
节点添加到“活动”的清单节点中)
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
or for Android 3.2 (API level 13) and newer :
(或适用于Android 3.2(API级别13)及更高版本 :)
<activity android:name=".MyActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name">
Then within the Activity override the onConfigurationChanged
method and call setContentView
to force the GUI layout to be re-done in the new orientation.
(然后在Activity中重写onConfigurationChanged
方法并调用setContentView
以强制以新方向重新完成GUI布局。)
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.myLayout);
}