android - Activity 生命周期 - onCreate 在每次重新定向时调用

标签 android activity-lifecycle

我有一个在 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/

相关文章:

android - 如何使用 ViewPager 将数据从 Activity 传递到 Tab Fragments?

android - 对 Android Activity 生命周期的困惑

Android - onStop() 将被延迟调用

java - 安卓 TCP 客户端。服务器仅在进程停止后接收消息

java - 将多个 SSL 证书固定添加到 Android KeyStore 不起作用。 (来自资源文件)

android - onPause() 是否保证被调用,即使在强制关闭应用程序进程时也是如此?

android - 如何覆盖 Android 应用程序中的配置?

java - 带有 java 集合的 OnSaveInstanceState/OnRestoreInstanceState

android - 标记似乎没有选择从和定位到计算和绘制谷歌地图中两个标记之间的路径

java - 我想获得特定月份的周数