I am writing a small android application that uses an asyncTask to display an image from a web service. The code works but it has been brought to my attention that I should recycle this bitmap.
My question is, is there a way to recycle this bitmap after I am done using it?
I attempted a solution using the onStop() and either the bitmap didn't get recycled or the image wouldn't display at all.
Here is my OnCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Other unrelated things
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
imageUrl = bundle.getString("imageUrl");
displayImage();
}
And here is my AsyncTask
private void displayImage() {
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... params) {
try {
return loadBitmap(params[0]);
} catch (Exception e) {
Logger.e(TAG, getString(R.string.error_loading_image_bitmap));
return null;
}
}
protected Bitmap loadBitmap(String urlSpec) throws IOException {
InputStream is = new URL(urlSpec).openStream();
try {
return BitmapFactory.decodeStream(is);
} finally {
is.close();
}
}
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
ImageView invoiceItemImageView = (ImageView) findViewById(R.id.some_id_here);
invoiceItemImageView.setImageBitmap(bitmap);
}
}
}.execute(imageUrl);
}
Override method View.onDetachedFromWindow()
and recycle your Bitmap
there.