我發現自己有類似的問題。經過一些研究和測試後,我想出了一些方法,而不是幫助我解決這個問題。那些正在使用單聲道的Android用C#實現的,但我想他們應該是幾乎相同的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個位圖所需的內存,其中兩個是第一個三倍大的內存。
/// <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());
}
一些語法更改後,在Java中正常工作。 –