内部类的安卓弱引用 [英] Android Weak Reference of Inner Class

查看:469
本文介绍了内部类的安卓弱引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过文章 http://developer.android不见了。 COM /资源/文章/避免内存-leaks.html 。在这篇文章中,建议使用静态内部类与弱引用。

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

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

}

这是不是正确的方法内部类弱参考?在上述code内存泄漏安全?

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

推荐答案

如果你只使用了 GalleryVideo 活动中的适配器对象,你并不需要使用弱引用。

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

您code段是内存泄漏的安全,这取决于你如何处理这些片断虽然你的应用程序是否在外面的对象。

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.

这篇关于内部类的安卓弱引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆