Activity Context 和 Application Context 的区别 [英] Difference between Activity Context and Application Context

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

问题描述

这让我很难过,我在 Android 2.1-r8 SDK 中使用了这个:

This has me stumped, I was using this in Android 2.1-r8 SDK:

ProgressDialog.show(getApplicationContext(), ....);

还有在

Toast t = Toast.makeText(getApplicationContext(),....);

使用 getApplicationContext() 使 ProgressDialogToast 都崩溃了......这让我想到了这个问题:

using getApplicationContext() crashes both ProgressDialog and Toast .... which lead me to this question:

尽管共享上下文"一词,但活动上下文和应用程序上下文之间的实际区别是什么?

What is the actual differences between a activity context and application context, despite sharing the wording 'Context'?

推荐答案

它们都是 Context,但是应用程序实例绑定到应用程序的生命周期,而Activity实例绑定到一个Activity的生命周期.因此,他们可以访问有关应用程序环境的不同信息.

They are both instances of Context, but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.

如果您阅读了 getApplicationContext 上的文档请注意,只有在需要生命周期与当前上下文分开的上下文时才应该使用它.这不适用于您的任何一个示例.

If you read the docs at getApplicationContext it notes that you should only use this if you need a context whose lifecycle is separate from the current context. This doesn't apply in either of your examples.

Activity 上下文大概有一些关于完成这些调用所必需的当前活动的信息.如果您显示确切的错误消息,也许能够指出它到底需要什么.

The Activity context presumably has some information about the current activity that is necessary to complete those calls. If you show the exact error message, might be able to point to what exactly it needs.

但一般来说,除非有充分的理由不使用,否则请使用活动上下文.

But in general, use the activity context unless you have a good reason not to.

这篇关于Activity Context 和 Application Context 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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