Android - Google's Contradiction on Singleton Pattern

后端 未结 2 767
迷失自我
迷失自我 2021-01-03 04:51

I\'ve been reading a bit about Singleton pattern usage in Android and its disadvantages regarding to keeping the Context. In fact, when I implement the following code:

相关标签:
2条回答
  • 2021-01-03 05:20

    Since Google is contradicting itself

    No, it is not.

    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).

    0 讨论(0)
  • 2021-01-03 05:32

    This is indeed a contradiction, since in many singletons you will need a context. Have a look at this post, I am using now this approach to avoid the warning in android studio:

    Android Singleton with Global Context

    0 讨论(0)
提交回复
热议问题