簡體   English   中英

清除內存中的圖像流

[英]Clearing image stream out of memory

因此,我有一個非常簡單的測試項目。 一個計時器,每個偶數迭代都會生成一個視圖,而每個奇數次迭代都會殺死該視圖。 視圖本身是帶有圖像的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調用imgStream.Close(); GC.SuppressFinalize(imgStream);GC.Collect(); )。 但是調用GC將導致明顯的滯后,此外,我不想擦除所有內容,而只是擦除流。 另外,它正在設備上運行。

Ty,Axel

我建議您檢查一下有關Android內存的簡短說明:

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

這很有趣,應該解釋為什么將圖像保留在垃圾收集器未清除的上下文中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM