厌世夕阳

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

  在使用Android WebView的时候,可能会造成Activity的内存泄漏,这个是Android的Bug,目前发现在WebView内部在使用TintResources时会发生内存泄漏,但是在appcompat-v7:23.2.1中已经修复了这个问题。所以当发生WebView的Context内存泄漏时,如果泄漏引用是来自TickResources时,可以将appcompat-v7包换成23.2.1或以上就可以解决了。具体原因我们可以来下源码:

  appcompat-v7 23.2.0 中的TintResources:

 1 public class TintResources extends Resources {
 2     private final Context mContext;
 3 
 4     public TintResources(@NonNull final Context context, @NonNull final Resources res) {
 5         super(res.getAssets(), res.getDisplayMetrics(), res.getConfiguration());
 6         mContext = context;
 7     }
 8 
 9     /**
10      * We intercept this call so that we tint the result (if applicable). This is needed for
11      * things like {@link android.graphics.drawable.DrawableContainer}s which can retrieve
12      * their children via this method.
13      */
14     @Override
15     public Drawable getDrawable(int id) throws NotFoundException {
16         return AppCompatDrawableManager.get().onDrawableLoadedFromResources(mContext, this, id);
17     }
18 
19     final Drawable superGetDrawable(int id) {
20         return super.getDrawable(id);
21     }
22 }

appcompat-v7 23.2.1中的TintResources:

 1 public class TintResources extends Resources {
 2     private final WeakReference<Context> mContextRef;
 3 
 4     public TintResources(@NonNull final Context context, @NonNull final Resources res) {
 5         super(res.getAssets(), res.getDisplayMetrics(), res.getConfiguration());
 6         mContextRef = new WeakReference<>(context);
 7     }
 8 
 9     /**
10      * We intercept this call so that we tint the result (if applicable). This is needed for
11      * things like {@link android.graphics.drawable.DrawableContainer}s which can retrieve
12      * their children via this method.
13      */
14     @Override
15     public Drawable getDrawable(int id) throws NotFoundException {
16         final Context context = mContextRef.get();
17         if (context != null) {
18             return AppCompatDrawableManager.get().onDrawableLoadedFromResources(context, this, id);
19         } else {
20             return super.getDrawable(id);
21         }
22     }
23 
24     final Drawable superGetDrawable(int id) {
25         return super.getDrawable(id);
26     }
27 }

可以很清楚的看的23.2.1版本只是将Context的强引用改成了弱引用来避免内存泄漏。

posted on 2016-04-14 12:58  厌世夕阳  阅读(357)  评论(0编辑  收藏  举报