我已经看完了文章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
Activity 中使用 Adapter 对象,则不需要使用弱引用。
您的代码 fragment 是内存泄漏安全的,这取决于您对该 fragment 之外的对象所做的操作,尽管您的应用程序是否是。
只需确保在 Activity 中创建的任何引用该 Activity(特别是包括非静态内部类和匿名类)的对象都不会离开 Activity。
关于Android内部类的弱引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5002350/