1

How safe is the Android's MutableContextWrapper to use in terms of memory leak etc? I am instantiating a WebView with an Activity's context and later want to change its context to another Activity.

Here is an answer that warns of using MutableContextWrapper for WebView as it can cause leaks with mix of contexts. But i dont see any reason as how can it cause leaks when we change its context? Why shouldnt we change a View's context once its been intialized?

Has anybody used in and faced any problems(specially for WebView)? Are there any precautionary measures while using it?Any data to share for this?

Doron Yakovlev Golani
  • 5,188
  • 9
  • 36
  • 60
Diffy
  • 2,339
  • 3
  • 25
  • 47

1 Answers1

1

Definitely not safe. There are actions on Context that require counter-actions in order to free up resources, e.g. Context.registerComponentCallabacks, Context.registerReceiver, and if you change the Context in the meantime, that means the counter-actions will not be called for the initial context, resulting in resource leaks. And WebView uses these actions, that's for sure.

Note that WebView is a much more complex component that a regular View, because it contains a network stack, a rendering engine, etc.

Mikhail Naganov
  • 6,643
  • 1
  • 26
  • 26
  • but AdMob is also using MutableContextWrapper. I checked it after decompiling the Google Play services code in a class which extends WebView. I can see there that they are instantiating that webview using MutableContextWrapper. – Diffy Dec 22 '15 at 07:08
  • As I understand, they sometimes need to use the Application context instead of the Activity context, that's why they use MutableContextWrapper. It's not for passing WebView between activities. – Mikhail Naganov Dec 22 '15 at 16:53
  • If they just need to use AppContext, they can save it in another variable and use it when required. But they are actually changing the context of WebView ( but in both cases they are using AppContext) – Diffy Dec 29 '15 at 08:51
  • Sorry for being unclear, by "they need to use" I actually meant that they need to pass a different context to WebView in certain situations. But it seems to be done only to work around some bugs. – Mikhail Naganov Dec 29 '15 at 19:03