Android Weak Reference of Inner Class

2019-03-30 06:57发布

问题:

I have gone through the article http://developer.android.com/resources/articles/avoiding-memory-leaks.html . In this article it is suggested to use static inner class with Weak Reference .

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){

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

}

Is it the correct way to inner class with weak ref.? Is the above code memory leak-safe?

回答1:

If you only use the Adapter object within the GalleryVideo activity, you don't need to use a weak reference.

Your code snippet is memory-leak safe, it depends on what you do with those objects outside that snippet though whether your application is.

Just make sure that no object created within an Activity that has a reference to that Activity (that especially includes non-static inner classes and anonymous classes) leaves the Activity.