Android 无法删除可提取的,虚拟机预算崩溃

Android 无法删除可提取的,虚拟机预算崩溃,android,imageview,android-linearlayout,Android,Imageview,Android Linearlayout,我正在开发一个应用程序,使用一种本地背景。这样做的目的是使这一点可以改变。我设法用这段代码更改“背景” Bitmap bMap = BitmapFactory.decodeFile(sharedPreferences.getString("PICTURE", "")); Drawable d =new BitmapDrawable(bMap); bac.setBackgroundDrawable(d); } 问题是每次我回到“背景屏幕”时,应用

我正在开发一个应用程序,使用一种本地背景。这样做的目的是使这一点可以改变。我设法用这段代码更改“背景”

Bitmap bMap = BitmapFactory.decodeFile(sharedPreferences.getString("PICTURE", ""));
        Drawable d =new BitmapDrawable(bMap);
        bac.setBackgroundDrawable(d);
        } 
问题是每次我回到“背景屏幕”时,应用程序都会因为OutOfMemoryError而崩溃。然后展示了新的背景。我需要一些代码,使应用程序不会崩溃。我可以在ImageView中实现这一点,但不能在LinearLayout中实现。对于ImageView,我使用以下代码:

Bitmap bMap = BitmapFactory.decodeFile(sharedPreferences.getString("PICTURE", ""));
    image.setImageBitmap(bMap);
为了避免它崩溃:

@Override
protected void onPause() {
super.onPause();

unbindDrawables(findViewById(R.id.iv_pic));
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();
    }
}
@Override
protected void onDestroy() {
super.onDestroy();

unbindDrawables(findViewById(R.id.iv_pic));
System.gc();

}
@覆盖
受保护的void onPause(){
super.onPause();
不可绑定的可提取文件(findViewById(R.id.iv_pic));
gc();
}
私有void未绑定可提取项(视图){
if(view.getBackground()!=null){
view.getBackground().setCallback(null);
}
if(视图组的视图实例){
对于(int i=0;i<((视图组)视图)。getChildCount();i++){
未绑定的Drawables(((视图组)视图).getChildAt(i));
}
((视图组)视图);
}
}
@凌驾
受保护的空onDestroy(){
super.ondestory();
不可绑定的可提取文件(findViewById(R.id.iv_pic));
gc();
}

如何对线性布局执行相同的操作?

关于OOM异常以及如何处理,有很多问题需要回答。发帖前请先回答问题

一些注意事项:

  • 您可以使用
    recycle
    方法释放
    位图所消耗的内存(在代码中,您可以调用
    bMap.recycle()
  • 您可以使用
    findViewById
    检索对
    LinearLayout的引用,并将其传递给
    unbindDrawables
    unbindDrawables(findViewById(R.id.myLinearLayoutId))