“Warning: Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)”

后端 未结 3 1791
甜味超标
甜味超标 2020-12-16 13:07

Similar question have been asked here, here and here but the context is quite different from this and moreover the code that gave from this error is written by the makers o

3条回答
  •  眼角桃花
    2020-12-16 14:02

    I found the solution to this in the answer to a similar question answered by CommonsWare

    I quote

    The quoted Lint warning is not complaining about creating singletons. It is complaining about creating singletons holding a reference to an arbitrary Context, as that could be something like an Activity. Hopefully, by changing mContext = context to mContext = context.getApplicationContext(), you will get rid of that warning (though it is possible that this still breaks Instant Run — I cannot really comment on that).

    Creating singletons is fine, so long as you do so very carefully, to avoid memory leaks (e.g., holding an indefinite static reference to an Activity).

    So Google is not actually contracting itself. To fix this, if this.getApplicationContext is supplied as a parameter for the context, then there will be no memory leak.

    So in essence, ignore the warning and supply this.getApplicationContext as a parameter for the context.

提交回复
热议问题