我有一个应用程序可以使用存储在 SD 卡上或直接存储在手机上的照片。
我有 2 个 Activity 似乎有某种问题(查看和编辑记录的 Activity )。单个记录通过存储提供相关照片位置的 URI 来引用照片。
当我点击我的 View Activity 时,我传递 URI,然后使用 URI 设置 ImageView。在查看 Activity 中时,我有一个菜单选项,可让您访问编辑 Activity 。当您单击“编辑”时,我再次传递照片的 URI,并使用该 URI 设置 ImageView。这两项 Activity 本身都表现良好。
但是,当我单击“后退”按钮从“编辑”移动到“查看”时,应用程序崩溃了。最初崩溃是一个 OutOfMemory 异常。我通过在两个 Activity 的 onPause 函数中添加对 ((BitmapDrawable)mImageView.getDrawable()).getBitmap().recycle()
的调用来克服此异常。
有了回收代码,执行从编辑移回 View ,然后就在某个地方崩溃了。我已经完成了生命周期函数,除了 onCreate 之外,执行成功了。执行再也不会到达 onCreate。
我知道它与 ImageView 相关,因为当我从我的 View Activity 中的布局中删除 ImageView 时,崩溃不再发生。
这是崩溃发生时的初始堆栈跟踪:
Thread [<3> main] (Suspended (exception RuntimeException))
ViewRoot.draw(boolean) line: 1356
ViewRoot.performTraversals() line: 1097
ViewRoot.handleMessage(Message) line: 1613
ViewRoot(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 123
ActivityThread.main(String[]) line: 4203
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 521
ZygoteInit$MethodAndArgsCaller.run() line: 791
ZygoteInit.main(String[]) line: 549
NativeStart.main(String[]) line: not available [native method]
在此堆栈跟踪之后,如果我继续在 Eclipse 中按“Step Over”,堆栈跟踪将像这样结束:
Thread [<3> main] (Suspended)
ThreadGroup.uncaughtException(Thread, Throwable) line: 884
NativeStart.main(String[]) line: not available [native method]
最佳答案
我找到了解决这个问题的方法。
部分归功于 Janusz 的回答,我能够找到其他解决方案。在我的 View 和编辑类中,我添加了一个私有(private)位图类变量 (mBitmap)。在 onCreate 中,我检索并存储图像位置的 URI。在 onPause 中,我回收位图。在 onResume 中,我更新了这个函数以使用新的类变量 mBitmap(我确信有更好的方法来设置位图,所以大家可以随意指出)。此外,使用这个新代码,我最初在 Edit 类中遇到了崩溃。如果您转到“编辑”,然后单击“主页”按钮,应用程序将会崩溃。我发现该问题的解决方案是在 Edit.onPause 中将 ImageView 的位图设置为 null。问题是 imageView 保留了指向位图的指针,即使在我回收位图之后也是如此。参见 Android "Trying to use recycled bitmap" error? :
protected void onResume()
{
mBitmap = null;
try
{
mBitmap = Bitmap.createBitmap(Media.getBitmap(this.getContentResolver(), mPicUri));
}
catch(Exception e)
{}
mImageView.setImageBitmap(mBitmap);
mImageView.setAdjustViewBounds(true);
mImageView.setMaxHeight(100); //purposely showing image as 100x100 picture
mImageView.setMaxWidth(100);
mImageView.invalidate();
super.onResume();
}
protected void onCreate()
{
mPicUri = //the picuture location URI
}
protected void onPause()
{
mBitmap.recycle();
mImageView.setImageBitmap(null); //in my Edit class
}
关于android - Android中的ImageView导致应用崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3183578/