getApplication() vs. getApplicationContext()

前端 未结 4 1051
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 08:39

I couldn\'t find a satisfying answer to this, so here we go: what\'s the deal with Activity/Service.getApplication() and Context.getApplicationContext()

4条回答
  •  悲哀的现实
    2020-11-22 09:46

    It seems to have to do with context wrapping. Most classes derived from Context are actually a ContextWrapper, which essentially delegates to another context, possibly with changes by the wrapper.

    The context is a general abstraction that supports mocking and proxying. Since many contexts are bound to a limited-lifetime object such as an Activity, there needs to be a way to get a longer-lived context, for purposes such as registering for future notifications. That is achieved by Context.getApplicationContext(). A logical implementation is to return the global Application object, but nothing prevents a context implementation from returning a wrapper or proxy with a suitable lifetime instead.

    Activities and services are more specifically associated with an Application object. The usefulness of this, I believe, is that you can create and register in the manifest a custom class derived from Application and be certain that Activity.getApplication() or Service.getApplication() will return that specific object of that specific type, which you can cast to your derived Application class and use for whatever custom purpose.

    In other words, getApplication() is guaranteed to return an Application object, while getApplicationContext() is free to return a proxy instead.

提交回复
热议问题