【发布时间】:2016-01-20 13:22:05
【问题描述】:
所以,我有一个非常简单的测试项目。一个计时器,每个偶数迭代都会生成一个视图,而每个奇数迭代都会终止该视图。视图本身是一个带有图像的 RelativeLayout。我想要做的是能够让这段时间无限期地运行而不会出现内存问题。问题是,我不知道如何真正清除用于从内存中创建位图的图像流。当我不再需要位图时,我正在回收它,但这还不够。代码在 C# (Xamarin) 中,但 java 的答案也有帮助。
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
RelativeLayout mainView = new RelativeLayout (this);
this.AddContentView(mainView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent));
...
int i = 0;
System.Timers.Timer t = new System.Timers.Timer (100);
t.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e) {
RunOnUiThread(delegate() {
if(i++ % 2 == 0){
tmpView tView = new tmpView(this);
mainView.AddView(tView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent));
}else{
((tmpView)mainView.GetChildAt(0)).dispose();
mainView.RemoveAllViews();
}
});
};
t.AutoReset = true;
t.Start ();
}
private class tmpView:RelativeLayout{
ImageView img;
Android.Graphics.Bitmap bmp;
public tmpView(Context cntx):base(cntx){
SetBackgroundColor(new Android.Graphics.Color(200, 0, 0, 200));
System.IO.Stream imgStream = Application.Context.Assets.Open ("backgroundLeft.png");
img = new ImageView(cntx);
bmp = Android.Graphics.BitmapFactory.DecodeStream (imgStream);
img.SetImageBitmap(bmp);
//bmp.Recycle();
imgStream.Close();
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent, 500);
lp.TopMargin = 150;
this.AddView(img, lp);
}
public void dispose(){
bmp.Recycle ();
img.SetImageDrawable (null);
}
}
另外,我之所以说图像流是导致内存泄漏的原因是因为我实际上能够让这个时间运行一整天。我必须在imgStream.Close();(GC.SuppressFinalize(imgStream); 和GC.Collect();)之后添加 GC 调用。但是调用 GC 会导致明显的延迟,此外,我不想擦除所有内容,只想擦除流。此外,这是在设备上运行的。
泰, 阿克塞尔
【问题讨论】:
标签: java c# android memory-leaks garbage-collection