从URl Android加载图像时出现内存泄漏
我目前正在使用Xamarin。开发我的android应用程序 我遇到的问题是,当我加载一堆图像时,它占用了我堆栈内存的很大一部分,并且无法正确重置。因此,如果应用程序从活动A启动,您转到活动B(加载图像),我将返回到活动A,然后返回到活动B,它将崩溃(内存不足问题)。我上传了一个演示应用程序,演示了我遇到的问题从URl Android加载图像时出现内存泄漏,android,memory-leaks,xamarin,Android,Memory Leaks,Xamarin,我目前正在使用Xamarin。开发我的android应用程序 我遇到的问题是,当我加载一堆图像时,它占用了我堆栈内存的很大一部分,并且无法正确重置。因此,如果应用程序从活动A启动,您转到活动B(加载图像),我将返回到活动A,然后返回到活动B,它将崩溃(内存不足问题)。我上传了一个演示应用程序,演示了我遇到的问题 namespace imageLoader { [Activity (Label = "LoadImages")] public class LoadImages
namespace imageLoader
{
[Activity (Label = "LoadImages")]
public class LoadImages : Activity
{
Bitmap image;
List<PromotionClass> pro;
PromotionAdapter proAdapter;
RadListView radlist;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.LoadImages);
LinearLayout line = (LinearLayout)FindViewById (Resource.Id.lin);
radlist = new RadListView (this);
GridLayoutManager gridLayoutManager = new GridLayoutManager(this,1,
LinearLayoutManager.Horizontal, false);
radlist.SetLayoutManager (gridLayoutManager);
pro = new List<PromotionClass>();
ArrayList a = new ArrayList ();
a.Add ("http://apk.payment24.co.za/promotions/nov/Zappar.jpg");
a.Add ("http://apk.payment24.co.za/promotions/nov/Valpre.jpg");
a.Add ("http://apk.payment24.co.za/promotions/nov/Tropika.jpg");
int dent = (int)Resources.DisplayMetrics.Density;
foreach (var url in a) {
image = GlobalMethods.GetImageBitmapFromUrl(url.ToString(),dent);
pro.Add(new PromotionClass("","",image));
}
proAdapter = new PromotionAdapter (pro, this);
radlist.SetAdapter (proAdapter);
line.AddView (radlist);
// Create your application here
}
public override void OnBackPressed ()
{
SetContentView (Resource.Layout.Main);
Intent intent = new Intent (this, typeof(LoadImages));
intent.AddFlags (ActivityFlags.NewTask);
intent.AddFlags (ActivityFlags.ClearTask);
intent.AddFlags (ActivityFlags.NoAnimation);
StartActivity (intent);
this.Finish ();
}
}
它还包含telerik dll文件 将加载的位图存储到缓存中,因此无需重新加载位图。
请参阅通过查看粘贴在此处的代码片段,另一个问题可能是“List()”每个都包含对“缩放”图像的引用,但这些图像似乎从未被释放/回收
你有没有尝试过让PromotionClass成为一次性的?然后在android活动的“OnDestroy()”方法中,您可以处理“PromotionClass”,而PromotionClass反过来可以回收/处理缩小的图像。我添加了代码,我只需使用UrlImageViewHelper为您处理所有这些:这是一个了不起的库。或者看看毕加索:
public static Bitmap GetImageBitmapFromUrl(string url,int dens)
{
Bitmap bitmapScaled = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
// Create an image from the Byte Array
Bitmap imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
bitmapScaled = Bitmap.CreateScaledBitmap(imageBitmap, imageBitmap.Height * dens, imageBitmap.Width * dens, true);
imageBitmap.Recycle();
}
}
// Return the new Scaled image
return bitmapScaled;
}