What is the difference between Activity and Context?

最后都变了- 提交于 2019-11-26 12:25:10

问题


Are Activity and Context the same, or are there differences?

When should I have a method pass an Activity, and when a Context?


回答1:


As far as I understand: Context is the Base Object. So every Activity same as Application derives from Context. This means that every Activity and every Application IS a Context;

From developer.android.com Activity

java.lang.Object
  ↳ android.content.Context
      ↳ android.content.ContextWrapper
          ↳ android.view.ContextThemeWrapper
              ↳ android.app.Activity

And Application

java.lang.Object
↳   android.content.Context
   ↳    android.content.ContextWrapper
       ↳    android.app.Application

An Application context lasts, as long as your app is alive, while the Activity context dies with your Activity (it is not valid after onDestroy of that Activity).

So if you need the Context across Activities (i.e. in a Singleton) you will be better off using an Application context.

Usually on Android Framework methods where a context is expected, it makes no difference which one you pass. But be always aware of MemoryLeaks if you're keeping long-living References to a Context




回答2:


As You can see on the Android doc:

The Activity class extends from "ContextThemeWrapper", and this one from "ContextWrapper", and that one from "Context".

So, yes, An Activity extends the Context!



来源:https://stackoverflow.com/questions/6518206/what-is-the-difference-between-activity-and-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!