我的应用程序中有各种图像,使用drawable i导入这些图像。但每当我尝试高分辨率的图像时,我经常会得到
09-02 11:52:09.289:E / AndroidRuntime(29749): java.lang.OutOfMemoryError:位图大小超过VM预算09-02 11:52:09.289:E / AndroidRuntime(29749):at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)09-02 11:52:09.289:E / AndroidRuntime(29749):at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:460)
对于这个特殊问题,当我移动到下一个活动时,我使用以下代码清除位图
protected void onPause() {
super.onPause();
MemoryClearManager.unbindDrawables(findViewById(R.id.mainlayout));
System.gc();
Runtime.getRuntime().gc();
}
public class MemoryClearManager {
/**
* @param view
* Removes callback on all the background drawables
* Removes child on every view group
*/
public static void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
try{
((ViewGroup) view).removeAllViews();
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
}
即使我这样做,我也无法解决内存问题。我可以在其他设备上运行相同的代码。任何人都可以指导我解决这个特殊问题。
提前致谢。
答案 0 :(得分:0)
试用此解码器
您可以传递要显示的尺寸。
public Bitmap decodeStream(InputStream is,int size) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null ,o);
// The new size we want to scale to
final int REQUIRED_SIZE = size;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(is, null ,o);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}