getContext(), getApplicationContext(), getBaseContext()和“this”之间的区别是什么?
虽然这是一个简单的问题,但我无法理解它们之间的基本区别。如果可能,请举一些简单的例子。
getContext(), getApplicationContext(), getBaseContext()和“this”之间的区别是什么?
虽然这是一个简单的问题,但我无法理解它们之间的基本区别。如果可能,请举一些简单的例子。
当前回答
上下文是:
一个抽象类,它的实现由Android系统提供。 它允许访问特定于应用程序的资源和类,以及 对应用程序级操作的向上调用,例如启动活动, 广播和接收意图等。
其他回答
“什么是Context”是Android世界中最难回答的问题之一。
上下文定义了访问系统资源、检索应用程序的静态资产、检查权限、执行UI操作等等的方法。从本质上讲,上下文是生产环境中上帝对象反模式的一个例子。
当涉及到我们应该使用哪种上下文时,它变得非常复杂,因为除了是上帝对象之外,上下文子类的层次树粗暴地违反了利斯科夫替换原则。
这篇博客文章(现在来自Wayback Machine)试图总结上下文类在不同情况下的适用性。
为了完整起见,让我从那篇文章中复制主表:
+----------------------------+-------------+----------+---------+-----------------+-------------------+ | | Application | Activity | Service | ContentProvider | BroadcastReceiver | +----------------------------+-------------+----------+---------+-----------------+-------------------+ | Show a Dialog | NO | YES | NO | NO | NO | | Start an Activity | NO¹ | YES | NO¹ | NO¹ | NO¹ | | Layout Inflation | NO² | YES | NO² | NO² | NO² | | Start a Service | YES | YES | YES | YES | YES | | Bind to a Service | YES | YES | YES | YES | NO | | Send a Broadcast | YES | YES | YES | YES | YES | | Register BroadcastReceiver | YES | YES | YES | YES | NO³ | | Load Resource Values | YES | YES | YES | YES | YES | +----------------------------+-------------+----------+---------+-----------------+-------------------+ An application CAN start an Activity from here, but it requires that a new task be created. This may fit specific use cases, but can create non-standard back stack behaviors in your application and is generally not recommended or considered good practice. This is legal, but inflation will be done with the default theme for the system on which you are running, not what’s defined in your application. Allowed if the receiver is null, which is used for obtaining the current value of a sticky broadcast, on Android 4.2 and above.
getApplicationContext ()
它用于应用程序级别,并引用所有活动。
全文()和全文()
很可能是相同的。这些只是指当前活动是活的。
this
总是引用当前类对象。
上下文是:
一个抽象类,它的实现由Android系统提供。 它允许访问特定于应用程序的资源和类,以及 对应用程序级操作的向上调用,例如启动活动, 广播和接收意图等。
这个:当前类对象
getContext():返回当前活动的上下文
getApplicationContext():返回应用程序中正在运行的所有活动
View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity. Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity. ContextWrapper.getBaseContext(): If you need access to a Context from within another context, you use a ContextWrapper. The Context referred to from inside that ContextWrapper is accessed via getBaseContext().