標籤:
在使用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 for11 * things like {@link android.graphics.drawable.DrawableContainer}s which can retrieve12 * their children via this method.13 */14 @Override15 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 for11 * things like {@link android.graphics.drawable.DrawableContainer}s which can retrieve12 * their children via this method.13 */14 @Override15 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的強引用改成了弱引用來避免記憶體流失。
Android TintResources Leak