我有一个在 onCreate
中加载位图的简单 Activity 。我发现如果我旋转设备,我可以从 onCreate
再次调用的日志中看到。事实上,因为所有实例变量都重新设置为默认值,我知道整个 Activity 已经被重新实例化了。
旋转 2 次后,我得到一个 FC,因为无法为位图分配足够的内存。 ( Activity 的所有实例都还在某处吗?还是 GC 清理的速度不够快?)
@Override
public void onCreate(Bundle savedInstanceState) {
File externalStorageDir = Environment.getExternalStorageDirectory();
File picturesDir = new File(externalStorageDir, "DCIM/Camera");
File[] files = picturesDir.listFiles(new FilenameFilter(){
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".jpg");
}});
if (files.length > 0) {
Bitmap bm = BitmapFactory.decodeStream(new FileInputStream(files[0]));
ImageView view = (ImageView) findViewById(R.id.photo);
view.setImageBitmap(bm);
}
}
从我阅读的所有内容来看,onCreate 应该在应用程序的生命周期内调用一次。我错了吗?重新定向设备如何导致重新创建 Activity ?
最佳答案
android:configChanges="keyboardHidden|orientation|screenSize"
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).
来自文档:http://developer.android.com/guide/topics/resources/runtime-changes.html
关于android - Activity 生命周期 - onCreate 在每次重新定向时调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7618703/