在生命周期事件期间,Activity 是否在 Android 中被销毁并重新创建?还是他们只是“重新依恋”了?
Do Activities get destroyed and recreated in Android during lifecycle events? Or do they simply get “re-attached”?
让我们考虑以下 Activity
的示例子类
public class CustomActivity extends Activity
{
private int myIntVar;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom);
if (myIntVar == 0)
{
Random rand = new Random();
int min = 1;
int max = 100;
myIntVar = rand.nextInt((max+1) - min) + min;
}
}
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
}
}
的官方文档
调用方法 onSaveInstanceState(...)
是为了让应用程序有时间在进入后台之前保存其当前状态。但是当前加载到内存中的 CustomActivity
的对象会发生什么?它是否也随着生命周期事件一起被创建和销毁?或者它是否永久保存在内存中(只要应用程序仍然处于活动状态 - 即使它在后台)并且它会在时间到来时简单地“重新附加”?
换句话说,在 Android 应用程序的整个生命周期中(从用户最初打开它到用户在 task-manager/menu 屏幕中将其滑开后关闭)将 myIntVar
只能设置一次,还是设置多次?
Does it also get created and destroyed alongside the lifecycle events?
是的。
Or is it preserved perpetually in memory (as long as the application is still active - even if it's in the background) and it will simply be "re-attached" when the time comes?
没有
Will myIntVar only be set once, or multiple times?
对于任何给定的 CustomActivity
实例,一次。在所有 CustomActivity
个实例中,多次。
让我们考虑以下 Activity
public class CustomActivity extends Activity
{
private int myIntVar;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom);
if (myIntVar == 0)
{
Random rand = new Random();
int min = 1;
int max = 100;
myIntVar = rand.nextInt((max+1) - min) + min;
}
}
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
}
}
的官方文档
调用方法 onSaveInstanceState(...)
是为了让应用程序有时间在进入后台之前保存其当前状态。但是当前加载到内存中的 CustomActivity
的对象会发生什么?它是否也随着生命周期事件一起被创建和销毁?或者它是否永久保存在内存中(只要应用程序仍然处于活动状态 - 即使它在后台)并且它会在时间到来时简单地“重新附加”?
换句话说,在 Android 应用程序的整个生命周期中(从用户最初打开它到用户在 task-manager/menu 屏幕中将其滑开后关闭)将 myIntVar
只能设置一次,还是设置多次?
Does it also get created and destroyed alongside the lifecycle events?
是的。
Or is it preserved perpetually in memory (as long as the application is still active - even if it's in the background) and it will simply be "re-attached" when the time comes?
没有
Will myIntVar only be set once, or multiple times?
对于任何给定的 CustomActivity
实例,一次。在所有 CustomActivity
个实例中,多次。