开发者

Android Weak Reference of Inner Class

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 sav开发者_StackOverflowedInstanceState) {

        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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜