据我所知,GC 会运行 VM 中的所有对象,如果没有对对象的引用,则会将其删除。Android Activity 有点不同,它有自己的生命周期。
当 Androids 需要更多 RAM 用于其他应用程序(活动)时,会在您的 Activity onSaveInstanceState (Bundle outState)
中调用。在这个地方你应该保存你需要的一切Bundle
当用户回到你的活动时你可以恢复那些对象onRestoreInstanceState(Bundle savedInstanceState)
。
编辑:以我的应用程序为例:
public class Window {
public Window(Bundle bundle) {
maximized = bundle.getBoolean("maximized", maximized);
displayed = bundle.getBoolean("displayed", displayed);
minimized = bundle.getBoolean("minimized", minimized);
resizable = bundle.getBoolean("resizable", resizable);
orientation = bundle.getInt("orientation");
}
public Bundle bundle() {
Bundle bundle = new Bundle();
bundle.putBoolean("maximized", maximized);
bundle.putBoolean("displayed", displayed);
bundle.putBoolean("minimized", minimized);
bundle.putBoolean("resizable", resizable);
bundle.putInt("orientation", orientation);
return bundle;
}
}
和 MainActivity:
public class MainActivity extends Activity {
ArrayList<Window> windows;
[...]
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Bundle[] windowsBundle = new Bundle[windows.size()];
for(int i=0; i<windowsBundle.length; i++){
windowsBundle[i] = windows.get(i).bundle();
}
savedInstanceState.putParcelableArray("windows", windowsBundle);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
Parcelable[] windowsParcels = savedInstanceState.getParcelableArray("windows");
Bundle[] windowsBundle = (Bundle[]) Arrays.copyOf(windowsParcels, windowsParcels.length, Bundle[].class);
windowsParcels = null;
for(int i=0; i<windowsBundle.length; i++){
windows.add(new Window(windowsBundle[i]));
}
}
}