Android Weak Reference of Inner Class

你。 提交于 2019-12-05 01:00:48

问题


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.



来源:https://stackoverflow.com/questions/5002350/android-weak-reference-of-inner-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!