【问题标题】:Clearing image stream out of memory清除内存中的图像流
【发布时间】: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


    【解决方案1】:

    我建议你看看这个关于 Android 内存的小讨论:

    https://realm.io/news/droidcon-ricau-memory-leaks-leakcanary/

    这很有趣,应该可以解释为什么您的图像会保留在垃圾收集器未清理的上下文中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      • 2013-06-23
      • 1970-01-01
      • 2020-12-14
      相关资源
      最近更新 更多