I have two simple activities A and B. The user starts B from A by pressing a button, and the user then returns to A by pressing the back button.
In the onDestroy() method of activity B I recycle some background images used in activity B. What I am trying to understand is why, when activity B is started again, I am getting ‘trying to use a recycled bitmap’. Surely the bitmaps will be loaded again in the onCreate() method? like they must have been on the first time the activity was launched.
Here is my example code:
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();
}
}
The code I use to launch activity B from A
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>
This part may be relevant. I’m not sure. I’ve noticed that after launching activity B, even after it has been destroyed, I can still see an instance of my activity when analyzing the memory heap using MAT. The path to GC roots seems to go through Java.lang.Thread and ContextImpl.
You get that error because
ImageView iv&LinearLayout llare still pointing to recycled bitmaps. You don’t need to do recycling yourself insideonDestroy(). Bitmaps will be freed when they are not needed by the system.