Pérdida de memoria de imagen de mapa de bits de Android
Pongo 4x4 imageView a una actividad (BoardActivity), y el usuario puede cambiar las imágenes haciendo clic en ellas. Con HTC Desire (Android 2.2.2), obtuve OOM (Out Of Memory) en aproximadamente 30 minutos de uso intensivo-EDIT: 16º inicio de esta actividad-, pero ningún otro dispositivo produce esto (android 2.1 y android 2.2.1). ¿Es posible que haya cometido algún error con el uso del mapa de bits / vista de imagen y que cause este error? Primero, cargo todos los ID de recursos en un mapa:
private Map<String, Integer> imageResourceMap;
imageResourceMap = new HashMap<String, Integer>();
imageResourceMap.put("a", R.drawable.a);
imageResourceMap.put("b", R.drawable.b);
imageResourceMap.put("c", R.drawable.c);
//... I store 55 drawable's resourceId in this map
Luego redimensiono y guardo cada imagen en un mapa de bits, representado en el Mapa:
private static Map<String, Bitmap> imageBitmap;
private void loadBitmaps(int imagesSize) {
for (String s : imageResourceMap.keySet()) {
Bitmap tmp = getBitmapFromRes(imageResourceMap.get(s), imagesSize);
imageBitmap.put(s, tmp);
}
}
private Bitmap getBitmapFromRes(int resId, int imageSize) {
Bitmap b = null;
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
InputStream fis = getResources().openRawResource(resId);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > imageSize || o.outWidth > imageSize) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(imageSize / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = getResources().openRawResource(resId);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return b;
}
Mantengo las imágenes vistas en una matriz, e inicio todas las imágenes con esta función:
private static ImageView[][] imageViews;
private ImageView getImage(String name) {
MyImageView item = new MyImageView(this, i, j, c + "");
item.setImageBitmap(imageBitmap.get(name));
item.setAdjustViewBounds(true);
return item;
}
Cuando necesito cambiar una imagen, simplemente cambio su recurso:
imageViews[i][j].setImageBitmap(imageBitmap.get("a"));
Y justo antes de que termine la actividad, reciclo el mapa de mapa de bits:
private void recycleImageBitmaps() {
for (Bitmap b : imageBitmap.values()) {
if (b != null) {
b.recycle();
}
}
}
En AndroidManifest.xml declaré esta actividad "singleTask":
<activity android:name=".game.board.BoardActivity" android:launchMode="singleTask">
</activity>
En esta aplicación (juego), reabrimos esta actividad varias veces ... ¿En qué me equivoqué? ¿Puede esto causar el error de memoria insuficiente?
CORRECCIÓN Corregido el getBitmapFromRes de esta manera:
private Bitmap getBitmapFromRes(int resId, int imageSize) {
Bitmap tmp = null;
Bitmap b = null;
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
InputStream fis = getResources().openRawResource(resId);
tmp = BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > imageSize || o.outWidth > imageSize) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(imageSize / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = getResources().openRawResource(resId);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(tmp != null){
tmp.recycle();
tmp = null;
}
}
return b;
}
HTC todavía se estrelló en el inicio 11 de esta actividad.
EDITAR: Esta actividad (BoardActivity) se inicia desde una Activity (MenuActivity), que tiene 4 imageButton, y está en una actividad de Tabhost. Las declaraciones de imageButtons se ven así:
<ImageButton
android:id="@+id/game_menu_CreateButton"
android:layout_width="120dip"
android:layout_height="120dip"
android:layout_alignRight="@+id/textView1"
android:layout_alignTop="@+id/textView1"
android:background="@drawable/create"
android:layout_marginRight="1sp"
android:layout_marginTop="10sp"
/>
Cuando inicio el BoardActivity desde MenuActivity, no llamofinish()
en MenuActivity, y cuando llamofinish()
en BoardActivity, no comienzo una nueva intención, por lo que simplemente vuelve a la MenuActivity ya abierta. Y la ronda 16 de esto, tengo el OOM.