你好,我知道这是一个重复的问题,但答案对我来说似乎并不适用 我的应用程序在第二次运行时崩溃,所以如果我运行它一旦它确定但当我关闭并再次运行它崩溃在日志猫给我这个错误 java.lang.OutOfMemoryError:位图大小超过VM预算 我尝试使用此代码
@Override
protected void onDestroy(){
// TODO Auto-generated method stub
super.onDestroy();
unbindDrawables(sView);
System.gc();
}
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
但是没有运气我使用surfaceview类在画布上绘制我的位图这是我的代码 私人SurfaceV sView;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
sView = new SurfaceV(this);
setContentView(sView);
}
并在sView类中
private SurfaceHolder holder;
private Thread thread = null;
private Canvas canvas;
private Bitmap background = BitmapFactory.decodeResource(getResources(), R.drawable.sky);
private Bitmap bg = Bitmap.createScaledBitmap(background, w, h, false);
private Bitmap sky = BitmapFactory.decodeResource(getResources(), R.drawable.sky2);
private Bitmap s = Bitmap.createBitmap(sky, 210, 10, 230, 230);
private Bitmap c1 = Bitmap.createBitmap(sky, 10, 14, 182, 100);
private Bitmap c2 = Bitmap.createBitmap(sky, 10, 142, 182, 100);
private Bitmap c3 = Bitmap.createBitmap(sky, 10, 292, 182, 112);
private Bitmap sun = Bitmap.createScaledBitmap(s, sunSize, sunSize, false);
private Bitmap cloud1 = Bitmap.createScaledBitmap(c1, cloudWidth, cloudHeigth, false);
private Bitmap cloud2 = Bitmap.createScaledBitmap(c2, cloudWidth, cloudHeigth, false);
private Bitmap cloud3 = Bitmap.createScaledBitmap(c3, cloudWidth, cloudHeigth, false);
public SurfaceV(Context context){
super(context);
holder = getHolder();
}
@Override
public void run(){
while(running){
if(!holder.getSurface().isValid()){
continue;
}
startTime = System.currentTimeMillis();
canvas = holder.lockCanvas();
draw(canvas);
holder.unlockCanvasAndPost(canvas);
doFpsCheck(startTime);
}
@Override
public void draw(Canvas canvas){
super.draw(canvas);
canvas.drawBitmap(bg, 0, 0, null);
canvas.drawBitmap(sun, 20, 20, null);
canvas.drawBitmap(cloud1, c1x, c1y, null);
canvas.drawBitmap(cloud2, c2x, c2y, null);
canvas.drawBitmap(cloud3, c3x, c3y, null);
}
请任何帮助将非常感谢您提前感谢
答案 0 :(得分:0)
使用Bitmaps时Android中的内存泄漏非常受欢迎。 这是因为您创建了许多位图,显示它们,但没有从内存中删除它们,所以突然间你会出现内存不足错误。
创建位图并绘制它们之后,您应该使用Recycle方法:
yourBitmap.recycle()
这是官方文件的形式:
“警告:只有在确定不再使用位图时才应使用recycle()。如果调用recycle()并稍后尝试绘制位图,则会出现错误:”Canvas:尝试使用回收的位图“
你可以在这里找到更多:
https://developer.android.com/training/displaying-bitmaps/manage-memory.html
希望它会有所帮助。