我有两个简单的活动A
和B
。用户按下按钮从A
启动B
,然后按返回按钮返回A
。
在活动B
的onDestroy()
方法中,我回收了活动B
中使用的一些背景图像。我想要理解的是为什么,当活动B
再次启动时,我正在"尝试使用回收位图"。当然,位图将在onCreate()方法中再次加载?就像他们第一次启动活动时一样。
public class ActivityB extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.selectionpage);
}
@Override
public void onDestroy() {
ImageView iv = (ImageView) findViewById(R.id.imageView1);
((BitmapDrawable)iv.getDrawable()).getBitmap().recycle();
LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout1);
((BitmapDrawable)ll.getBackground()).getBitmap().recycle();
super.onDestroy();
}
}
我用来从A
启动活动B
的代码
Intent intent = new Intent(ActivityA.this, ActivityB.class);
startActivity(intent);
selectionpage.XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/backgroundimage">
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/selectionimage"/>
</LinearLayout>
这部分可能是相关的。我不确定。我注意到,在启动活动B之后,即使在它被销毁之后,我仍然可以在使用MAT分析内存堆时看到我的活动实例。到GC根的路径似乎通过Java.lang.Thread和ContextImpl.
你会得到这个错误,因为ImageView iv
&LinearLayout ll
仍然指向回收位图。你不需要在onDestroy()
里面自己做回收。当系统不需要位图时,位图将被释放。
如果你在一个单独的线程中有一个活动的引用,该线程保留该活动的时间超过了它应该保留的时间,那么你可能会有内存泄漏。
这可能导致旧活动中的iv和ll在回收后仍在使用位图。你可以做iv.setImageDrawable(null)和ll.setBackgroundDrawable(null),但这些位图是由系统创建的,你不应该需要回收它们。
我猜你试图回收它们,因为你遇到了内存问题?
必须用代码来完成。在代码中初始化Bitmap对象并使用Imageview.setImageBitmap(Bitmap)
Bitmap bitmap;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectionpage);
bitmap = new BitmapFactory.decode...
yourImageView.setImageBitmap(bitmap);
}
@Override
public void onDestroy() {
super.onDestroy();
// do recycle bitmap here
bitmap.recycle();
}