一些设备的配置可以在运行时改变(比如屏幕方向,键盘可用性和语言)。当这样的变化发生,安卓重启运行的Activity(onDestroy方法被调用,随后是onCreate)。重启行为设计为帮助我们的应用适应新的配置,通过自动加载匹配新设备配置的替代资源。
为了合理处理重启,我们的活动在他的正常活动生命周期恢复之前状态是非常重要的,在生命周期中,安卓调用onSaveInstanceState在它销毁我们的活动前,这样我们可以保存关于应用状态的数据。(这个方法不保证调用,所有只有一些临时数据,如果要持久化数据到数据库,还是需要在onPause方法的)。我们然后就可以在onCreate和onRestoreInstanceState之间恢复状态。
为了测试我们的应用能够保持应用状态原封不动重启,我们应该激活设置变化(比如改变屏幕方向)当在应用中执行各种任务。我们的应用应该在任何时间重启并且没有用户数据和状态丢失为了处理事件,比如配置改变或者当用户接收一个来电并且在程序可能已经被销毁了很久才回来。所有活动的生命周期处理很重要,要继续学习啊。(这个恢复,那么保存的信息是在哪里,是系统帮我们保存,然后我们从系统中取吗?)
然而,我们可能遇到一个情况,重启应用恢复相当大量的数据可能很耗时,导致用户体验差。在这种情况下,有两种选择:
a. Retain an object during a configuration change
允许我们的活动重启当一个配置改变,但是携带一个状态完好的对象给活动的新实例。
b. Handle the configuration change yourself
阻止系统重启我们的活动在特定配置变化时,但是接收一个回调当配置改变,这样我们可以手工更新活动如果有需要。
Retaining an Object During a Configuration Change
________________________________________
如果重启我们的活动要求回复大量数据,重建新的网络连接,或者执行其他集中操作,然后一个由于配置改变的完全重启可能会减慢用户体验。另外,或许不可能完全恢复活动状态使用系统在onSaveInstanceState回调方法保存的Bundle,它不是设计用来携带大对象(比如bitmaps)和数据要先序列化然后反序列化,会消耗很多内存导致配置变化很慢。在这种情况下,我们可以减轻重启活动的负担通过保留一个Fragment当我们的活动因为配置改变重启。这个Fragment可以包含一个我们想保存的全状态对象的引用。
当系统因为配置改变关闭我们的系统,活动中的我们用来标记保存的碎片没有销毁。我们可以添加一个这样的碎片到我们的活动来保存全状态对象。
为了在运行时配置改变时在一个碎片获得全状态对象:
1. 继承Fragment类,并且声明一个到我们全状态对象的引用。
2. 调用setRetainInstance(boolean)当碎片创建(就是在onCreate方法中).
3. 添加碎片到活动.
4. 使用FragmentManager重获碎片当活动重启。
下面是一个Fragment例子:
public class RetainedFragment extends Fragment {
// data object we want to retain
private MyDataObject data;
// this method is only called once for this fragment
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retain this fragment
setRetainInstance(true);
}
public void setData(MyDataObject data) {
this.data = data;
}
public MyDataObject getData() {
return data;
}
}
Caution:因为我们可以保存任何对象,我们应该绝不传送一个对象绑定到这个活动上,比如一个Drawable,一个Adapter,一个View或者任何关联到一个Context(接口,需要学习)的对象。如果我们这样做,它会泄露原始活动实例的所有的view和资源。(泄露资源意味着我们的应用维护他们,并且他们不能垃圾回收,所以大量内存会丢失)。
然后,使用FragmentManager去添加这个碎片到活动。我们可以在运行时配置改变活动重启时,从这个碎片获得数据对象。例如,这样定义我们的活动:
在这个例子中,onCreate方法添加一个碎片或者还原一个他的引用。onCreate也在碎片实例中保存全状态对象。onDestroy更新保存在碎片实例的全状态对象。
(第一次要在碎片中设置我们的数据,使用loadMydata方法活动的数据;此后,活动每次销毁都要重新设置数据,使用collectMyLoadedData方法,挺好的)
Handling the Configuration Change Yourself
________________________________________
如果我们的应用不需要在一个特定配置变化更新资源,并且我们有一个行为限制,要求避免活动重启,然后我们可以声明我们的活动自己处理配置变化,阻止系统重启我们的活动。
Note:自己处理配置变化可能让使用替代资源更困难,因为系统不自动为我们应用他们。这个技巧应该深思熟虑作为最后的手段当我们必须避免重启因为一个配置变化并且对于多数应用不推荐。下面我就暂时不浪费时间了,有精力在看吧。
To declare that your activity handles a configuration change, edit the appropriate <activity> element in your manifest file to include the android:configChanges attribute with a value that represents the configuration you want to handle. Possible values are listed in the documentation for the android:configChanges attribute (the most commonly used values are "orientation" to prevent restarts when the screen orientation changes and "keyboardHidden" to prevent restarts when the keyboard availability changes). You can declare multiple configuration values in the attribute by separating them with a pipe | character.
For example, the following manifest code declares an activity that handles both the screen orientation change and keyboard availability change:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
Now, when one of these configurations change, MyActivity does not restart. Instead, the MyActivity receives a call to onConfigurationChanged(). This method is passed a Configuration object that specifies the new device configuration. By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface. At the time this method is called, your activity's Resources object is updated to return resources based on the new configuration, so you can easily reset elements of your UI without the system restarting your activity.
Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must decalare android:configChanges="orientation|screenSize". However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).
For example, the following onConfigurationChanged() implementation checks the current device orientation:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
The Configuration object represents all of the current configurations, not just the ones that have changed. Most of the time, you won't care exactly how the configuration has changed and can simply re-assign all your resources that provide alternatives to the configuration that you're handling. For example, because the Resources object is now updated, you can reset any ImageViews with setImageResource() and the appropriate resource for the new configuration is used (as described in Providing Resources).
Notice that the values from the Configuration fields are integers that are matched to specific constants from the Configuration class. For documentation about which constants to use with each field, refer to the appropriate field in the Configuration reference.
Remember: When you declare your activity to handle a configuration change, you are responsible for resetting any elements for which you provide alternatives. If you declare your activity to handle the orientation change and have images that should change between landscape and portrait, you must re-assign each resource to each element during onConfigurationChanged().
If you don't need to update your application based on these configuration changes, you can instead not implement onConfigurationChanged(). In which case, all of the resources used before the configuration change are still used and you've only avoided the restart of your activity. However, your application should always be able to shutdown and restart with its previous state intact, so you should not consider this technique an escape from retaining your state during normal activity lifecycle. Not only because there are other configuration changes that you cannot prevent from restarting your application, but also because you should handle events such as when the user leaves your application and it gets destroyed before the user returns to it.
为了合理处理重启,我们的活动在他的正常活动生命周期恢复之前状态是非常重要的,在生命周期中,安卓调用onSaveInstanceState在它销毁我们的活动前,这样我们可以保存关于应用状态的数据。(这个方法不保证调用,所有只有一些临时数据,如果要持久化数据到数据库,还是需要在onPause方法的)。我们然后就可以在onCreate和onRestoreInstanceState之间恢复状态。
为了测试我们的应用能够保持应用状态原封不动重启,我们应该激活设置变化(比如改变屏幕方向)当在应用中执行各种任务。我们的应用应该在任何时间重启并且没有用户数据和状态丢失为了处理事件,比如配置改变或者当用户接收一个来电并且在程序可能已经被销毁了很久才回来。所有活动的生命周期处理很重要,要继续学习啊。(这个恢复,那么保存的信息是在哪里,是系统帮我们保存,然后我们从系统中取吗?)
然而,我们可能遇到一个情况,重启应用恢复相当大量的数据可能很耗时,导致用户体验差。在这种情况下,有两种选择:
a. Retain an object during a configuration change
允许我们的活动重启当一个配置改变,但是携带一个状态完好的对象给活动的新实例。
b. Handle the configuration change yourself
阻止系统重启我们的活动在特定配置变化时,但是接收一个回调当配置改变,这样我们可以手工更新活动如果有需要。
Retaining an Object During a Configuration Change
________________________________________
如果重启我们的活动要求回复大量数据,重建新的网络连接,或者执行其他集中操作,然后一个由于配置改变的完全重启可能会减慢用户体验。另外,或许不可能完全恢复活动状态使用系统在onSaveInstanceState回调方法保存的Bundle,它不是设计用来携带大对象(比如bitmaps)和数据要先序列化然后反序列化,会消耗很多内存导致配置变化很慢。在这种情况下,我们可以减轻重启活动的负担通过保留一个Fragment当我们的活动因为配置改变重启。这个Fragment可以包含一个我们想保存的全状态对象的引用。
当系统因为配置改变关闭我们的系统,活动中的我们用来标记保存的碎片没有销毁。我们可以添加一个这样的碎片到我们的活动来保存全状态对象。
为了在运行时配置改变时在一个碎片获得全状态对象:
1. 继承Fragment类,并且声明一个到我们全状态对象的引用。
2. 调用setRetainInstance(boolean)当碎片创建(就是在onCreate方法中).
3. 添加碎片到活动.
4. 使用FragmentManager重获碎片当活动重启。
下面是一个Fragment例子:
public class RetainedFragment extends Fragment {
// data object we want to retain
private MyDataObject data;
// this method is only called once for this fragment
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retain this fragment
setRetainInstance(true);
}
public void setData(MyDataObject data) {
this.data = data;
}
public MyDataObject getData() {
return data;
}
}
Caution:因为我们可以保存任何对象,我们应该绝不传送一个对象绑定到这个活动上,比如一个Drawable,一个Adapter,一个View或者任何关联到一个Context(接口,需要学习)的对象。如果我们这样做,它会泄露原始活动实例的所有的view和资源。(泄露资源意味着我们的应用维护他们,并且他们不能垃圾回收,所以大量内存会丢失)。
然后,使用FragmentManager去添加这个碎片到活动。我们可以在运行时配置改变活动重启时,从这个碎片获得数据对象。例如,这样定义我们的活动:
在这个例子中,onCreate方法添加一个碎片或者还原一个他的引用。onCreate也在碎片实例中保存全状态对象。onDestroy更新保存在碎片实例的全状态对象。
(第一次要在碎片中设置我们的数据,使用loadMydata方法活动的数据;此后,活动每次销毁都要重新设置数据,使用collectMyLoadedData方法,挺好的)
Handling the Configuration Change Yourself
________________________________________
如果我们的应用不需要在一个特定配置变化更新资源,并且我们有一个行为限制,要求避免活动重启,然后我们可以声明我们的活动自己处理配置变化,阻止系统重启我们的活动。
Note:自己处理配置变化可能让使用替代资源更困难,因为系统不自动为我们应用他们。这个技巧应该深思熟虑作为最后的手段当我们必须避免重启因为一个配置变化并且对于多数应用不推荐。下面我就暂时不浪费时间了,有精力在看吧。
To declare that your activity handles a configuration change, edit the appropriate <activity> element in your manifest file to include the android:configChanges attribute with a value that represents the configuration you want to handle. Possible values are listed in the documentation for the android:configChanges attribute (the most commonly used values are "orientation" to prevent restarts when the screen orientation changes and "keyboardHidden" to prevent restarts when the keyboard availability changes). You can declare multiple configuration values in the attribute by separating them with a pipe | character.
For example, the following manifest code declares an activity that handles both the screen orientation change and keyboard availability change:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
Now, when one of these configurations change, MyActivity does not restart. Instead, the MyActivity receives a call to onConfigurationChanged(). This method is passed a Configuration object that specifies the new device configuration. By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface. At the time this method is called, your activity's Resources object is updated to return resources based on the new configuration, so you can easily reset elements of your UI without the system restarting your activity.
Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must decalare android:configChanges="orientation|screenSize". However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).
For example, the following onConfigurationChanged() implementation checks the current device orientation:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
The Configuration object represents all of the current configurations, not just the ones that have changed. Most of the time, you won't care exactly how the configuration has changed and can simply re-assign all your resources that provide alternatives to the configuration that you're handling. For example, because the Resources object is now updated, you can reset any ImageViews with setImageResource() and the appropriate resource for the new configuration is used (as described in Providing Resources).
Notice that the values from the Configuration fields are integers that are matched to specific constants from the Configuration class. For documentation about which constants to use with each field, refer to the appropriate field in the Configuration reference.
Remember: When you declare your activity to handle a configuration change, you are responsible for resetting any elements for which you provide alternatives. If you declare your activity to handle the orientation change and have images that should change between landscape and portrait, you must re-assign each resource to each element during onConfigurationChanged().
If you don't need to update your application based on these configuration changes, you can instead not implement onConfigurationChanged(). In which case, all of the resources used before the configuration change are still used and you've only avoided the restart of your activity. However, your application should always be able to shutdown and restart with its previous state intact, so you should not consider this technique an escape from retaining your state during normal activity lifecycle. Not only because there are other configuration changes that you cannot prevent from restarting your application, but also because you should handle events such as when the user leaves your application and it gets destroyed before the user returns to it.
本文介绍如何在安卓应用中处理配置改变导致的Activity重启问题,包括使用onSaveInstanceState方法保存状态,利用Fragment保留对象状态,及自行处理配置改变避免重启。
1084

被折叠的 条评论
为什么被折叠?



