活动和上下文有什么区别? [英] What is the difference between Activity and Context?

查看:29
本文介绍了活动和上下文有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Activity 和 Context 是一样的还是有区别的?

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

什么时候应该让方法传递一个活动,什么时候传递一个上下文?

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

推荐答案

据我所知:Context 是基础对象.所以每个 ActivityApplication 派生自 Context.这意味着每个 Activity 和每个 Application 都是一个 Context;

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;

来自 developer.android.com 活动

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

应用

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

只要您的应用程序处于活动状态,应用程序上下文就会持续存在,而 Activity 上下文会随着您的 Activity 消失(在该 Activity 的 onDestroy 之后无效).

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.

通常在需要上下文的 Android 框架方法上,传递哪个没有区别.但请始终注意 MemoryLeaks 如果您要保留对上下文的长期引用

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

这篇关于活动和上下文有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆