我发现自己也有类似的问题。经过一些研究和测试,我想出了一些方法来帮助我解决这个问题。这些是使用 C# 使用 Mono for Android 实现的,但我想它们应该与 Java 几乎相同:
/// <summary>
///Calculates the memory bytes used by the given Bitmap.
/// </summary>
public static long GetBitmapSize(Android.Graphics.Bitmap bmp)
{
return GetBitmapSize(bmp.Width, bmp.Height, bmp.GetConfig());
}
/// <summary>
///Calculates the memory bytes used by a Bitmap with the given specification.
/// </summary>
public static long GetBitmapSize(long bmpwidth, long bmpheight, Android.Graphics.Bitmap.Config config)
{
int BytesxPixel = (config == Android.Graphics.Bitmap.Config.Rgb565) ? 2 : 4;
return bmpwidth * bmpheight * BytesxPixel;
}
/// <summary>
///Calculates the memory available in Android's VM.
/// </summary>
public static long FreeMemory()
{
return Java.Lang.Runtime.GetRuntime().MaxMemory() - Android.OS.Debug.NativeHeapAllocatedSize;
}
/// <summary>
///Checks if Android's VM has enough memory for a Bitmap with the given specification.
/// </summary>
public static bool CheckBitmapFitsInMemory(long bmpwidth, long bmpheight, Android.Graphics.Bitmap.Config config)
{
return (GetBitmapSize(bmpwidth, bmpheight, config) < FreeMemory());
}
该代码被证明非常可靠,可以防止内存不足异常。下面的代码片段是在名为Utils的命名空间中使用这些方法的示例。此代码计算 3 个位图所需的内存,其中两个是第一个的 3 倍。
/// <summary>
/// Checks if there's enough memory in the VM for managing required bitmaps.
/// </summary>
private bool NotEnoughMemory()
{
long bytes1 = Utils.GetBitmapSize(this.Width, this.Height, BitmapConfig);
long bytes2 = Utils.GetBitmapSize(this.Width * 3, this.Height * 3, BitmapConfig);
return ((bytes1 + bytes2 + bytes2) >= Utils.FreeMemory());
}