其他分享
首页 > 其他分享> > 内在类的Android弱参考

内在类的Android弱参考

作者:互联网

我已经阅读了文章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){

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

}

对于弱参照的内部类,它是正确的方法吗?以上代码内存是否泄漏安全?

解决方法:

如果仅在GalleryVideo活动中使用Adapter对象,则无需使用弱引用.

您的代码段是内存泄漏安全的,它取决于您对该代码段之外的那些对象所执行的操作,不管您的应用程序是否正常.

只需确保在Activity中没有创建任何对象,该对象具有对该Activity的引用(特别是包括非静态内部类和匿名类)离开Activity.

标签:android,memory-leaks,static,inner-classes,weak-references
来源: https://codeday.me/bug/20190704/1382126.html