如何释放位图占用的内存

how to release memory occupied by bitmaps

我正在创建一个以循环方式显示图像视图的应用程序。它显示设置图标,例如蓝牙、wifi 等。没有内存不足错误,但在完成 activity 后,应用程序仍然使用大约。根据内存分析器工具,位图上有 15mb RAM。怎么样,我可以释放那些位图吗

这是创建圆形视图的代码:

    settingsImageViews = new ArrayList<View>(0);

    // create settings icon views
    for (int i = 0; i <= 12; i++) {
        ImageView imageView = new ImageView(this);
        if (i > 2 && i != 10) {
            imageView.setImageDrawable(getSettingsIcon(i - 3));
        } else if (i == 10) {
            imageView.setImageDrawable(getResources().getDrawable(R.drawable.ic_key));
        } else {
            imageView.setImageDrawable(null);
        }

        settingsImageViews.add(imageView);
    }

    settingsCircularView = new CircleView(this, CIRCLE_RADIUS, settingsImageViews);
    parentLayout.addView(settingsCircularView);

对于循环视图,我正在使用此代码:custom circular view. placing of views

getSettingsIcon方法:

private Drawable getSettingsIcon(int settingId) {
    switch (settingId) {

    case 0:// bluetooth
        if (PhoneSetting.isBluetoothOn())
            return getResources().getDrawable(R.drawable.ic_bluetooth);
        else
            return getResources().getDrawable(R.drawable.ic_bluetooth_off);

    case 1:// wifi
        if (wifiManager.isWifiEnabled())
            return getResources().getDrawable(R.drawable.ic_wifi_on);
        else
            return getResources().getDrawable(R.drawable.ic_wifi_off);
    .
    .
    .
    }
}

我试图在 onDestroy 方法中回收位图,但是当我重新打开 activity 时,它因 trying to use a recycled bitmap android.graphics.Bitmap 错误而崩溃。

我什至尝试调用 System.gc(),但应用程序仍然使用 15mb 内存。

我还使用 unbindDrawables 方法销毁了 onDestroy 中的所有视图:

private 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));
                }
                ((ViewGroup) view).removeAllViews();
        }
}

在尝试了以上所有方法后,连 1 MB 都没有减少。这些资源也使用大约。 4.5 兆

您是否遇到 OOM 问题?

由于您正在使用 getDrawable(R.drawable.superAwesomeFractal) Android 维护位图缓存——例如,如果您在两个不同的 ImageView 上设置相同的可绘制对象 Android 没有分配 space 的两倍。也就是说,由于您没有显式 creating/decoding/using 位图,除非您看到诸如 OOM 异常之类的实际问题,否则您不必担心释放它们或回收它们的分配——Android 将处理那是给你的。这就是为什么您在尝试重用回收位图时遇到异常的原因。