安卓内部类弱引用

4
我已经阅读了这篇文章:http://developer.android.com/resources/articles/avoiding-memory-leaks.html。在这篇文章中建议使用具有弱引用的静态内部类。
public class GalleryVideo extends Activity {

    private int AUDIO_NO = 1; 
    ...........................
    ................  

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        gallery = (Gallery) findViewById(R.id.examplegallery);
    gallery.setAdapter(new AddImgAdp(this));
    }



    static  public class AddImgAdp extends BaseAdapter {

    private int GalItemBg;
        private Context cont;
        private WeakReference<GalleryVideo> mGalleryVideo;

        public AddImgAdp(Context c) {

            mGalleryVideo = new WeakReference<GalleryVideo>(c);

            TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
            GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
            typArray.recycle();
        }


        public long getItemId(int position) {

            final GalleryVideo galleryVideo = mGalleryVideo.get();
            if(galleryVideo == null){

              if(galleryVideo.AUDIO_NO==4){

               ..................
               ...............
              }
            }
       }
   }

}

使用弱引用来定义内部类是正确的方式吗?上述代码是否具有防止内存泄漏的安全性?

1个回答

2

如果您只在GalleryVideo活动中使用适配器对象,则不需要使用弱引用。

您的代码片段是内存泄漏安全的,但取决于您在该片段之外对这些对象执行的操作,以确定您的应用程序是否安全。

请确保在活动中创建的任何对象都不会离开该活动(特别是非静态内部类和匿名类)。


1
你能详细说明一下:“这取决于你在外部如何处理这些对象......”吗?谢谢。 - Yaqub Ahmad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接