简体   繁体   English

Activity 和 Context 有什么区别?

[英]What is the difference between Activity and Context?

Are Activity and Context the same, or are there differences? Activity 和 Context 是一样的,还是有区别的?

When should I have a method pass an Activity, and when a Context?我应该什么时候让一个方法传递一个活动,什么时候传递一个上下文?

As far as I understand: Context is the Base Object.据我了解:上下文是基础 Object。 So every Activity same as Application derives from Context.所以每一个和Application一样的Activity都是从Context派生的。 This means that every Activity and every Application IS a Context ;这意味着每个 Activity 和每个Application都是一个Context

From developer.android.com Activity来自developer.android.com 。android.com 活动

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).只要您的应用程序还活着,应用程序上下文就会持续存在,而 Activity 上下文会随着您的 Activity 消失(在该 Activity 的onDestroy之后无效)。

So if you need the Context across Activities (ie 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.通常在需要上下文的 Android 框架方法上,通过哪一个没有区别。 But be always aware of MemoryLeaks if you're keeping long-living References to a Context但是,如果您要保持对上下文的长期引用,请始终注意MemoryLeaks

As You can see on the Android doc :正如您在Android 文档中看到的那样:

The Activity class extends from "ContextThemeWrapper", and this one from "ContextWrapper", and that one from "Context".活动 class 扩展自“ContextThemeWrapper”,这个来自“ContextWrapper”,而那个来自“Context”。

So, yes, An Activity extends the Context!所以,是的,一个活动扩展了上下文!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM