Android 上的“上下文”是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3572463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:48:33  来源:igfitidea点击:

What is 'Context' on Android?

androidandroid-context

提问by Brigadier

In Android programming, what exactly is a Contextclass and what is it used for?

在Android编程中,Context类到底是什么,它有什么用途?

I read about it on the developer site, but I am unable to understand it clearly.

我在开发者网站上读到过它,但我无法清楚地理解它。

采纳答案by Sameer Segal

Putting it simply:

简单来说:

As the name suggests, it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity and package/application).

顾名思义,它是应用程序/对象当前状态的上下文。它让新创建的对象了解发生了什么。通常,您调用它来获取有关程序另一部分(活动和包/应用程序)的信息。

You can get the context by invoking getApplicationContext(), getContext(), getBaseContext()or this(when in a class that extends from Context, such as the Application, Activity, Service and IntentService classes).

您可以通过调用获取上下文getApplicationContext()getContext()getBaseContext()this(当在扩展,从一类Context,如应用程序,活动,服务和IntentService类)。

Typical uses of context:

上下文的典型用途:

  • Creating new objects: Creating new views, adapters, listeners:

    TextView tv = new TextView(getContext());
    ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);
    
  • Accessing standard common resources: Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:

    context.getSystemService(LAYOUT_INFLATER_SERVICE)
    getApplicationContext().getSharedPreferences(*name*, *mode*);
    
  • Accessing components implicitly: Regarding content providers, broadcasts, intent

    getApplicationContext().getContentResolver().query(uri, ...);
    
  • 创建新对象:创建新视图、适配器、侦听器:

    TextView tv = new TextView(getContext());
    ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);
    
  • 访问标准公共资源:诸如 LAYOUT_INFLATER_SERVICE、SharedPreferences 之类的服务:

    context.getSystemService(LAYOUT_INFLATER_SERVICE)
    getApplicationContext().getSharedPreferences(*name*, *mode*);
    
  • 隐式访问组件:关于内容提供者、广播、意图

    getApplicationContext().getContentResolver().query(uri, ...);
    

回答by Devrath

Definition of Context

上下文的定义

  • Context represents environment data
  • It provides access to things such as databases
  • Context 代表环境数据
  • 它提供对诸如数据库之类的东西的访问

Simpler terms (example 1)

更简单的术语(示例 1)

  • Consider Person-X is the CEO of a start-up software company.

  • There is a lead architect present in the company, this lead architect does all the work in the company which involves such as database, UI etc.

  • Now the CEO Hires a new Developer.

  • It is the Architect who tells the responsibility of the newly hired person based on the skills of the new person that whether he will work on Database or UI etc.

  • 假设 Person-X 是一家初创软件公司的 CEO。

  • 公司有一个首席架构师,这个首席架构师负责公司的所有工作,包括数据库、UI 等。

  • 现在 CEO 聘请了一位新的开发人员。

  • 是架构师根据新人的技能告诉新人的职责,他是在数据库还是UI等方面工作。

Simpler terms (example 2)

更简单的术语(示例 2)

  • It's like access of android activity to the app's resource.

  • It's similar to when you visit a hotel, you want breakfast, lunch & dinner in the suitable timings, right?

  • There are many other things you like during the time of stay. How do you get these things?

  • You ask the room-service person to bring these things for you.

  • Here the room-service person is the context considering you are the single activity and the hotel to be your app, finally the breakfast, lunch & dinner have to be the resources.

  • 这就像 android 活动对应用程序资源的访问。

  • 这类似于您访问酒店时,您希望在合适的时间享用早餐,午餐和晚餐,对吗?

  • 在逗留期间,您还有很多其他喜欢的事情。你怎么得到这些东西?

  • 您要求客房服务人员为您带来这些东西。

  • 在这里,客房服务人员是上下文,考虑到您是单一活动,酒店是您的应用程序,最后,早餐、午餐和晚餐必须是资源。



Things that involve context are:

涉及上下文的事情是:

  1. Loading a resource.
  2. Launching a new activity.
  3. Creating views.
  4. obtaining system service.
  1. 加载资源。
  2. 开展一项新活动。
  3. 创建视图。
  4. 获取系统服务。


Context is the base class for Activity, Service, Application, etc

Context 是ActivityServiceApplication等的基类

Another way to describe this: Consider context as remote of a TV & channel's in the television are resources, services, using intents etc - - - Here remote acts as an access to get access to all the different resources into foreground.

另一种描述方式:将上下文视为电视和电视频道的远程资源,服务,使用意图等 - - - 这里远程充当访问所有不同资源的访问权限。

  • So, Remote has access to channels such as resources, services, using intents etc ....

  • Likewise ... Whoever has access to remote naturally has access to all the things such as resources, services, using intents etc

  • 因此,Remote 可以访问资源、服务、使用意图等渠道......

  • 同样......谁有权访问远程自然就可以访问所有事物,例如资源、服务、使用意图等



Different methods by which you can get context

获取上下文的不同方法

  • getApplicationContext()
  • getContext()
  • getBaseContext()
  • or this(when in the activity class)
  • getApplicationContext()
  • getContext()
  • getBaseContext()
  • this(在活动课上时)


Example:

例子:

TextView tv = new TextView(this);

The keyword thisrefers to the context of the current activity.

关键字this指的是当前活动的上下文。

回答by Sourab Sharma

Source

来源



The topic of Context in Android seems to be confusing to many. People just know that Context is needed quite often to do basic things in Android. People sometimes panic because they try to do perform some operation that requires the Context and they don't know how to “get” the right Context. I'm going to try to demystify the idea of Context in Android. A full treatment of the issue is beyond the scope of this post, but I'll try to give a general overview so that you have a sense of what Context is and how to use it. To understand what Context is, let's take a look at the source code:

Android 中的 Context 话题似乎让很多人感到困惑。人们只知道 Context 经常需要在 Android 中做基本的事情。人们有时会感到恐慌,因为他们试图执行一些需要 Context 的操作,但他们不知道如何“获取”正确的 Context。我将尝试揭开 Android 中 Context 的神秘面纱。对这个问题的全面处理超出了本文的范围,但我将尝试给出一个总体概述,以便您了解 Context 是什么以及如何使用它。要了解什么是Context,我们先来看一下源码:

https://github.com/android/platform_frameworks_base/blob/master/core/java/android/content/Context.java

https://github.com/android/platform_frameworks_base/blob/master/core/java/android/content/Context.java

What exactly is Context?

上下文究竟是什么?

Well, the documentation itself provides a rather straightforward explanation: The Context class is an “Interface to global information about an application environment".

嗯,文档本身提供了一个相当简单的解释:Context 类是“关于应用程序环境的全局信息的接口”。

The Context class itself is declared as abstract class, whose implementation is provided by the Android OS. The documentation further provides that Context “…allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc".

Context 类本身被声明为抽象类,其实现由 Android 操作系统提供。该文档进一步规定 Context “......允许访问特定于应用程序的资源和类,以及对应用程序级操作的调用,例如启动活动、广播和接收意图等”。

You can understand very well, now, why the name is Context. It's because it's just that. The Context provides the link or hook, if you will, for an Activity, Service, or any other component, thereby linking it to the system, enabling access to the global application environment. In other words: the Context provides the answer to the components question of “where the hell am I in relation to app generally and how do I access/communicate with the rest of the app?” If this all seems a bit confusing, a quick look at the methods exposed by the Context class provides some further clues about its true nature.

现在,您可以很好地理解为什么名称是 Context。正因为如此。如果您愿意,上下文为活动、服务或任何其他组件提供链接或挂钩,从而将其链接到系统,从而能够访问全局应用程序环境。换句话说:上下文提供了组件问题的答案:“我到底在哪里与应用程序相关,我如何访问/与应用程序的其余部分通信?” 如果这一切看起来有点令人困惑,快速查看 Context 类公开的方法会提供一些有关其真实性质的进一步线索。

Here's a random sampling of those methods:

这是这些方法的随机抽样:

  1. getAssets()
  2. getResources()
  3. getPackageManager()
  4. getString()
  5. getSharedPrefsFile()
  1. getAssets()
  2. getResources()
  3. getPackageManager()
  4. getString()
  5. getSharedPrefsFile()

What do all these methods have in common? They all enable whoever has access to the Context to be able to access application-wide resources.

所有这些方法有什么共同点?它们都使有权访问 Context 的任何人都能够访问应用程序范围的资源。

Context, in other words, hooks the component that has a reference to it to the rest of application environment. The assets (think '/assets' folder in your project), for example, are available across the application, provided that an Activity, Service or whatever knows how to access those resources. Same goes for getResources()which allows to do things like getResources().getColor()which will hook you into the colors.xmlresource (nevermind that aapt enables access to resources via java code, that's a separate issue).

换句话说,上下文将引用它的组件挂钩到应用程序环境的其余部分。例如,资产(例如项目中的“/assets”文件夹)在整个应用程序中都是可用的,前提是 Activity、Service 或任何知道如何访问这些资源的东西。这同样适用于getResources()允许做一些事情,比如getResources().getColor()将你连接到colors.xml资源中(不要介意 aapt 允许通过 java 代码访问资源,这是一个单独的问题)。

The upshot is that Contextis what enables access to system resources and its what hooks components into the “greater app". Let's look at the subclasses of Context, the classes that provide the implementation of the abstract Contextclass. The most obvious class is the Activityclass. Activityinherits from ContextThemeWrapper, which inherits from ContextWrapper, which inherits from Contextitself. Those classes are useful to look at to understand things at a deeper level, but for now it's sufficient to know that ContextThemeWrapperand ContextWrapperare pretty much what they sound like. They implement the abstract elements of the Contextclass itself by “wrapping” a context (the actual context) and delegating those functions to that context. An example is helpful - in the ContextWrapperclass, the abstract method getAssetsfrom the Contextclass is implemented as follows:

结果是,Context它能够访问系统资源,并将组件挂接到“更大的应用程序”中。让我们看看 的子Context类,提供抽象Context类实现的类。最明显的类是Activity类。Activity继承from ContextThemeWrapper, 继承自ContextWrapper, 继承自Context自身。这些类对于在更深层次上理解事物很有用,但现在知道这一点就足够了,ContextThemeWrapper而且ContextWrapper几乎就是它们听起来的样子。它们实现了抽象元素Context通过“包装”上下文(实际上下文)并将这些函数委托给该上下文来类本身。一个例子很有帮助 - 在ContextWrapper类,抽象方法getAssetsContext类是这样实现的:

@Override
    public AssetManager getAssets() {
        return mBase.getAssets();
    }

mBaseis simply a field set by the constructor to a specific context. So a context is wrapped and the ContextWrapperdelegates its implementation of the getAssets method to that context. Let's get back to examining the Activityclass which ultimately inherits from Contextto see how this all works.

mBase只是构造函数为特定上下文设置的字段。因此,一个上下文被包装,并且ContextWrapper将其 getAssets 方法的实现委托给该上下文。让我们回到检查Activity最终继承自的类,Context看看这一切是如何工作的。

You probably know what an Activity is, but to review - it's basically 'a single thing the user can do. It takes care of providing a window in which to place the UI that the user interacts with'. Developers familiar with other APIs and even non-developers might think of it vernacularly as a “screen.” That's technically inaccurate, but it doesn't matter for our purposes. So how do Activityand Contextinteract and what exactly is going in their inheritance relationship?

您可能知道 Activity 是什么,但回顾一下 - 它基本上是“用户可以做的一件事情”。它负责提供一个窗口,在该窗口中放置用户与之交互的 UI”。熟悉其他 API 的开发人员甚至非开发人员都可能将其视为“屏幕”。这在技术上是不准确的,但对我们的目的来说并不重要。那么,如何才能ActivityContext相互作用,并在他们的继承关系到底是怎么回事?

Again, it's helpful to look at specific examples. We all know how to launch Activities. Provided you have “the context” from which you are starting the Activity, you simply call startActivity(intent), where the Intent describes the context from which you are starting an Activity and the Activity you'd like to start. This is the familiar startActivity(this, SomeOtherActivity.class).

同样,查看具体示例很有帮助。我们都知道如何启动活动。如果您拥有启动 Activity 的“上下文”,您只需调用startActivity(intent),其中 Intent 描述您启动 Activity 的上下文以及您想要启动的 Activity。这是熟悉的startActivity(this, SomeOtherActivity.class)

And what is this? thisis your Activity because the Activityclass inherits from Context. The full scoop is like this: When you call startActivity, ultimately the Activityclass executes something like this:

什么是thisthis是您的 Activity,因为Activity该类继承自Context. 完整的独家新闻是这样的:当您调用 时startActivityActivity该类最终会执行如下操作:

Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode);

So it utilizes the execStartActivityfrom the Instrumentationclass (actually from an inner class in Instrumentationcalled ActivityResult).

所以它利用execStartActivity来自Instrumentation类(实际上来自Instrumentation被调用的内部类ActivityResult)。

At this point, we are beginning to get a peek at the system internals.

在这一点上,我们开始窥视系统内部。

This is where OS actually handles everything. So how does Instrumentation start the Activity exactly? Well, the param thisin the execStartActivitymethod above is your Activity, i.e. the Context, and the execStartActivitymakes use of this context.

这是操作系统实际处理一切的地方。那么 Instrumentation 究竟是如何启动 Activity 的呢?那么,帕拉姆thisexecStartActivity上述方法是你的活动,即环境,并且execStartActivity利用这一背景下的。

A 30,000 overview is this: the Instrumentation class keeps tracks of a list of Activities that it's monitoring in order to do it's work. This list is used to coordinate all of the activities and make sure everything runs smoothly in managing the flow of activities.

一个 30,000 的概述是这样的:Instrumentation 类跟踪它正在监视的活动列表,以便完成它的工作。此列表用于协调所有活动,并确保在管理活动流程时一切顺利。

There are some operations which I haven't fully looked into which coordinate thread and process issues. Ultimately, the ActivityResultuses a native operation - ActivityManagerNative.getDefault().startActivity()which uses the Contextthat you passed in when you called startActivity. The context you passed in is used to assist in “intent resolution” if needed. Intent resolution is the process by which the system can determine the target of the intent if it is not supplied. (Check out the guide here for more details).

有一些操作我还没有完全研究哪些协调线程和进程问题。最终,ActivityResult使用本机操作 -ActivityManagerNative.getDefault().startActivity()它使用Context您在调用时传入的startActivity。如果需要,您传入的上下文将用于协助“意图解析”。意图解析是系统可以在未提供意图的情况下确定意图目标的过程。(查看此处的指南了解更多详情)。

And in order for Android to do this, it needs access to information that is supplied by Context. Specifically, the system needs to access to a ContentResolverso it can “determine the MIME type of the intent's data". This whole bit about how startActivitymakes use of context was a bit complicated and I don't fully understand the internals myself. My main point was just to illustrate how application-wide resources need to be accessed in order to perform many of the operations that are essential to an app. Contextis what provides access to these resources. A simpler example might be Views. We all know what you create a custom View by extending RelativeLayoutor some other Viewclass, you must provide a constructor that takes a Contextas an argument. When you instantiate your custom View you pass in the context. Why? Because the View needs to be able to have access to themes, resources, and other View configuration details. View configuration is actually a great example. Each Context has various parameters (fields in Context's implementations) that are set by the OS itself for things like the dimension or density of the display. It's easy to see why this information is important for setting up Views, etc.

为了让 Android 做到这一点,它需要访问由Context. 具体来说,系统需要访问 aContentResolver以便它可以“确定意图数据的 MIME 类型”。关于如何startActivity使用上下文的整个部分有点复杂,我自己并不完全了解内部。我的主要观点只是为了说明需要如何访问应用程序范围的资源才能执行对应用程序至关重要的许多操作。Context提供对这些资源的访问权限。一个更简单的示例可能是视图。我们都知道您创建了什么通过扩展RelativeLayout或其他一些View类自定义视图 ,您必须提供一个构造函数,该构造函数采用Context作为论据。当您实例化自定义视图时,您将传入上下文。为什么?因为 View 需要能够访问主题、资源和其他 View 配置详细信息。视图配置实际上是一个很好的例子。每个 Context 都有各种参数(实现中的字段Context),这些参数由 OS 本身设置,用于显示的尺寸或密度等内容。很容易理解为什么这些信息对于设置视图等很重要。

One final word:For some reason people new to Android (and even people not so new) seem to completely forget about object-oriented programming when it comes to Android. For some reason, people try to bend their Android development to pre-conceived paradigms or learned behaviors.

最后一句话:出于某种原因,刚接触 Android 的人(甚至不那么陌生的人)在谈到 Android 时似乎完全忘记了面向对象编程。出于某种原因,人们试图将他们的 Android 开发转变为先入为主的范式或习得的行为。

Android has it's own paradigm and a certain pattern that is actually quite consistent if let go of your pre-conceived notions and simply read the documentation and dev guide. My real point, however, while “getting the right context” can sometimes be tricky, people unjustifiably panic because they run into a situation where they need the context and think they don't have it. Once again, Java is an object-oriented language with an inheritance design.

Android 有它自己的范式和特定的模式,如果放弃你的先入为主的观念,只需阅读文档和开发指南,这些模式实际上是非常一致的。然而,我真正的观点是,虽然“获得正确的上下文”有时会很棘手,但人们会不合理地感到恐慌,因为他们遇到了需要上下文并认为他们没有的情况。再一次,Java 是一种具有继承设计的面向对象语言。

You only “have” the context inside of your Activity because your activity itself inherits from Context. There's no magic to it (except for the all the stuff the OS does by itself to set various parameters and to correctly “configure” your context). So, putting memory/performance issues aside (e.g. holding references to context when you don't need to or doing it in a way that has negative consequences on memory, etc), Context is an object like any other and it can be passed around just like any POJO (Plain Old Java Object). Sometimes you might need to do clever things to retrieve that context, but any regular Java class that extends from nothing other than Object itself can be written in a way that has access to context; simply expose a public method that takes a context and then use it in that class as needed. This was not intended as an exhaustive treatment on Context or Android internals, but I hope it's helpful in demystifying Context a little bit.

您只在 Activity 内部“拥有”上下文,因为您的 Activity 本身继承自 Context。它没有什么神奇之处(除了操作系统自己为设置各种参数和正确“配置”您的上下文所做的所有工作)。因此,将内存/性能问题放在一边(例如,在不需要时保留对上下文的引用或以对内存产生负面影响的方式进行引用等),上下文是一个像任何其他对象一样的对象,它可以被传递就像任何 POJO(Plain Old Java Object)一样。有时您可能需要做一些聪明的事情来检索该上下文,但是任何从 Object 本身扩展而来的常规 Java 类都可以以可以访问上下文的方式编写;只需公开一个接受上下文的公共方法,然后根据需要在该类中使用它。

回答by angryITguy

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. An Android app has activities. Context is like a handle to the environment your application is currently running in. The activity object inherits the Context object.

上下文是系统的句柄;它提供诸如解析资源、获取对数据库和首选项的访问权等服务。Android 应用程序具有活动。Context 就像是您的应用程序当前运行的环境的句柄。活动对象继承了 Context 对象。

For more information, look in Introduction to Android development with Android Studio - Tutorial.

有关更多信息,请查看Android Studio 开发简介 - 教程

回答by Dmytro Danylyk

Contextis an "interface" to the global information about an application environment. In practice, Contextis actually an abstract class, whose implementation is provided by the Android system.

Context是有关应用程序环境的全局信息的“接口”。实际上,Context实际上是一个抽象类,其实现由Android系统提供。

It allows access to application-specific resources and classes, as well as up-calls for application-level operations, such as launching activities, broadcasting and receiving intents, etc.

它允许访问特定于应用程序的资源和类,以及对应用程序级操作的调用,例如启动活动、广播和接收意图等。

In the following picture, you can see a hierarchy of classes, where Contextis the root class of this hierarchy. In particular, it's worth emphasizing that Activityis a descendant of Context.

在下图中,您可以看到一个Context类的层次结构,该层次结构的根类在哪里。特别值得强调的是,它ActivityContext.

Activity diagram

活动图

回答by s0ld13r

What's Contextexactly?

究竟是Context什么?

Per the Android reference documentation, it's an entity that represents various environment data. It provides access to local files, databases, class loaders associated to the environment, services (including system-level services), and more. Throughout this book, and in your day-to-day coding with Android, you'll see the Context passed around frequently.

根据 Android 参考文档,它是一个表示各种环境数据的实体。它提供对本地文件、数据库、与环境关联的类加载器、服务(包括系统级服务)等的访问。在整本书中,以及在您使用 Android 进行的日常编码中,您会看到 Context 经常被传递。

From the "Android in Practice" book, p. 60.

来自“ Android in Practice”一书,第 10 页。60.

Several Android APIs require a Contextas parameter

几个 Android API 需要一个Contextas 参数

If you look through the various Android APIs, you'll notice that many of them take an android.content.Contextobject as a parameter. You'll also see that an Activity or a Service is usually used as a Context. This works because both of these classes extend from Context.

如果您浏览各种 Android API,您会注意到它们中的许多都将android.content.Context对象作为参数。您还会看到 Activity 或 Service 通常用作 Context. 这是有效的,因为这两个类都从Context.

回答by Parsania Hardik

Simple Example to understand contextin android :

context在android中理解的简单示例:

Every boss has an assistant to look after, to do all less important and time-consuming tasks. If a file or a cup of coffee is needed, an assistant is on the run. Some bosses barely know what's going on in the office, so they ask their assistants regarding this too. They do some work themselves but for most other things they need the help of their assistants.

每个老板都有一个助手需要照顾,负责处理所有不太重要和耗时的任务。如果需要文件或一杯咖啡,助手会在运行。一些老板几乎不知道办公室里发生了什么,所以他们也向他们的助手询问此事。他们自己做一些工作,但对于大多数其他事情,他们需要助手的帮助。

In this scenario,

在这种情况下,

Boss – is the Android application

Boss – 是 Android 应用程序

Assistant – is context

助手 - 是上下文

Files/Cup of coffee – are resources

文件/一杯咖啡——是资源

We generally call context when we need to get information about different parts of our application like Activities, Applications etc.

当我们需要获取有关应用程序不同部分(如活动、应用程序等)的信息时,我们通常会调用上下文。

Some operations(things where the assistant is needed) where context is involved:

一些涉及上下文的操作(需要助手的地方):

  • Loading common resources
  • Creating dynamic views
  • Displaying Toast messages
  • Launching Activities etc.
  • 加载公共资源
  • 创建动态视图
  • 显示 Toast 消息
  • 启动活动等

Different ways of getting context:

获取上下文的不同方式:

getContext()

getBaseContext()

getApplicationContext()

this

回答by naikus

An Android Contextis an Interface(in the general sense, not in the Java sense; in Java, Contextis actually an abstract class!) that allows access to application specific resources and class and information about application environment.

Android Context是一个接口(一般意义上,不是 Java 意义上的;在 Java 中,Context实际上是一个抽象类!),它允许访问应用程序特定的资源和类以及有关应用程序环境的信息。

If your android app was a web app, your context would be something similar to ServletContext(I am not making an exact comparison here).

如果您的 android 应用程序是一个网络应用程序,您的上下文将类似于ServletContext(我没有在此处进行精确比较)。

Your activities and services also extend Context, so they inherit all those methods to access the environment information in which the app is running.

您的活动和服务也会扩展Context,因此它们会继承所有这些方法来访问应用程序运行所在的环境信息。

回答by naikus

  • Contextrepresents a handle to get environment data .
  • Contextclass itself is declared as abstract, whose implementation is provided by the android OS.
  • Contextis like remote of a TV & channel's in the television are resources, services, etc. enter image description here
  • Context表示获取环境数据的句柄。
  • Context类本身被声明为抽象类,其实现由 android 操作系统提供。
  • Context就像电视的遥控器和电视中的频道是资源、服务等。 在此处输入图片说明

What can you do with it ?

你能用它做什么?

  • Loading resource.
  • Launching a new activity.
  • Creating views.
  • Obtaining system service.
  • 正在加载资源。
  • 开展一项新活动。
  • 创建视图。
  • 获取系统服务。

Ways to get context :

获取上下文的方法:

  • getApplicationContext()
  • getContext()
  • getBaseContext()enter image description hereenter image description here
  • getApplicationContext()
  • getContext()
  • getBaseContext()在此处输入图片说明在此处输入图片说明

回答by star18bit

Just putting it out there for newbies;

只是把它放在那里给新手;

So First understand Word Context :

所以首先了解词上下文:

In english-lib. it means:

在英文库中。它的意思是:

"The circumstances that form the setting for an event, statement, or idea, and in terms of which it can be fully understood and assessed."

"The parts of something written or spoken that immediately precede and follow a word or passage and clarify its meaning."

“形成事件、陈述或想法的背景的情况,并且可以根据这些情况完全理解和评估。”

“在一个词或一段话之前和之后,并阐明其含义的书面或口语部分。”

Now take the same understanding to programming world:

现在对编程世界采取同样的理解:

context of current state of the application/object. It lets newly created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity, package/application)

应用程序/对象当前状态的上下文。它让新创建的对象了解发生了什么。通常,您调用它来获取有关程序另一部分(活动、包/应用程序)的信息

You can get the context by invoking getApplicationContext(), getContext(), getBaseContext()or this(when in the activity class).

您可以通过调用getApplicationContext(),getContext(), getBaseContext()this(在活动类中时)来获取上下文。

To Get Context Anywhere in application use following code:

要在应用程序中的任何地方获取上下文,请使用以下代码:

Create new class AppContextinside your android application

AppContext在您的 android 应用程序中创建新类

public class AppContext extends Application {

    private static Context context;

    public void onCreate(){
        super.onCreate();
        AppContext.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return AppContext.context;
    }
}

Now any time you want application context in non-activity class, call this method and you have application context.

现在任何时候你想要非活动类中的应用程序上下文,调用这个方法,你就有了应用程序上下文。

Hope this help ;)

希望这有帮助;)