什么是“上下文”?在安卓上?

发布于 2024-10-03 15:47:22 字数 175 浏览 4 评论 0原文

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

橘香 2024-10-10 15:47:23

只是为新手提供的;

所以首先了解单词上下文:

在 english-lib 中。这意味着:

“构成事件、陈述或事件背景的环境
想法,并据此可以充分理解和评估它。”

“紧接在和之前的书面或口头内容的部分
跟随一个单词或一段话并阐明其含义。”

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

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

您可以通过调用 getApplicationContext()getContext()、getBaseContext()this< 来获取上下文/code> (当在活动类中时)。

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

在 Android 应用程序中创建新类 AppContext

public class AppContext extends Application {

    private static Context context;

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

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

现在,只要您需要在非活动类中使用应用程序上下文,请调用这个方法和你有应用程序上下文

希望这有帮助;)

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).

To Get Context Anywhere in application use following code:

Create new class AppContext inside your android application

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 ;)

杯别 2024-10-10 15:47:23

将其视为隔离了运行应用程序或服务的进程的虚拟机。隔离环境可以访问一堆底层系统信息和某些允许的资源。您需要该上下文才能获得这些服务。

Think of it as the VM that has siloed the process the app or service is running in. The siloed environment has access to a bunch of underlying system information and certain permitted resources. You need that context to get at those services.

梦里梦着梦中梦 2024-10-10 15:47:23

上下文是对当前对象的引用,如下所示。上下文还允许访问有关应用程序环境的信息。

Context is a reference to the current object as this. Also context allows access to information about the application environment.

戈亓 2024-10-10 15:47:23

android.content.Context 类提供与 Android 系统和项目资源的连接。它是有关应用程序环境的全局信息的接口。

Context 还提供对 Android 服务的访问,例如位置服务。

活动和服务扩展了Context 类。

The class android.content.Context provides the connection to the Android system and the resources of the project. It is the interface to global information about the application environment.

The Context also provides access to Android Services, e.g. the Location Service.

Activities and Services extend the Context class.

黯然 2024-10-10 15:47:23

Context 是 Android 提供的一个抽象类,因此,它的作用是将您的应用程序代码与 Android 系统连接起来。通过从 Context(活动、服务和应用程序)继承的类,您的应用程序能够访问只能由操作系统访问的资源和功能。

当上下文后代对象被操作系统实例化时(通过操作系统控制的实例化机制,如“意图”),它们将由操作系统管理,因此它们获得生命周期。

对于其他任何事情,在方法调用中将上下文作为参数传递,允许此方法使用上下文作为与操作系统通信的通道,以便到达操作系统并要求它执行某些操作或返回一些资源。

将上下文与清单一起可视化

在此处输入图像描述

为了可视化运行中的 Android 上下文和清单,旧的呼叫中心总机是一个很好的类比。

基础是 Android 系统,连接每个正在运行的应用程序的所有应用程序组件的所有电线都出现在其中。

  1. 每个“总机应用程序”都包含一些插件,它们代表应用程序的清单组件声明。因此,通过清单声明,Android 系统了解这些插头的存在,以便它可以通过意图创建对象来插入新的上下文线。

  2. 每条线代表一个连接到应用程序的某些可启动组件或应用程序本身的 Android 上下文。您可以使用现有的线路,因为它与 Android 系统连接,以便请求需要通过操作系统完成的各种事情。

  3. 您可以假设当一个 Activity 被销毁时,它的电线就会被拔掉。当构造另一个活动(或另一个组件)时,会出现一条新线并连接到正确的清单声明的插头。

我写了整篇文章来解释上下文如何将您的应用程序耦合到 Android 系统

The Context is an abstract class provided by Android, and as such, its job is to bridge your application code with the Android System. Through classes that inherit from Context (activities, services, and your application), your app gains the ability to access resources and functionalities reachable only by the Operating System.

When context descendant objects get instantiated by the Operating System (through an OS controlled instantiation mechanism, like "intents"), they become administered by the Operating System, and as such, they obtain lifecycle.

For anything else, passing a context as a parameter in method calls, allows this method to use the context as a channel of communication with the OS, in order to reach the OS and ask it to perform some action or return some resource.

Visualising the Context together with the Manifest

enter image description here

To visualize the Android Context and Manifest in action, an old calling centre switchboard is a great analogy.

The base is the Android System, where all the wires connecting all the application components of every running app, emerge.

  1. Each "switchboard application" contains some plugholes, which represent the app's manifest component declarations. So through manifest declarations, the Android System learns about the existence of these plugholes so it can plug a new context wire by creating objects through intents.

  2. Each wire represents an Android Context connected to some launchable component of the app, or to the app itself. You can use an existing wire since it is connected with the Android System, in order to request all kinds of things that need to go through the Operating System, to be accomplished.

  3. You can assume that when an activity is destroyed, its wire gets unplugged. While when another activity (or another component) is constructed, a new wire emerges and connects to the correct manifest-declared plughole.

I have written an entire article that explains how the Context couples your app to the android system:

谁的年少不轻狂 2024-10-10 15:47:23

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

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

这是示例

 public class MyActivity extends Activity {

      public void Testing() {

      Context actContext = this; /*returns the Activity Context since   Activity extends Context.*/

      Context appContext = getApplicationContext();    /*returns the context of the single, global Application object of the current process. */

      Button BtnShowAct1 = (Button) findViewById(R.id.btnGoToAct1);
      Context BtnContext = BtnShowAct1.getContext();   /*returns the context of the View. */

有关更多详细信息,您可以访问 http://developer.android .com/reference/android/content/Context.html

Context is an interface to global information about an application environment. It's an abstract class whose implementation is provided by the Android system.

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

Here is Example

 public class MyActivity extends Activity {

      public void Testing() {

      Context actContext = this; /*returns the Activity Context since   Activity extends Context.*/

      Context appContext = getApplicationContext();    /*returns the context of the single, global Application object of the current process. */

      Button BtnShowAct1 = (Button) findViewById(R.id.btnGoToAct1);
      Context BtnContext = BtnShowAct1.getContext();   /*returns the context of the View. */

For more details you can visit http://developer.android.com/reference/android/content/Context.html

墨落画卷 2024-10-10 15:47:23

Context 是 android.content.Context 类的实例,提供与执行应用程序的 Android 系统的连接。例如,您可以通过 Context 检查当前设备显示的大小。

它还允许访问项目的资源。它是有关应用程序环境的全局信息的接口。

Context 类还提供对 Android 服务的访问,例如,警报管理器以触发基于时间的事件。

活动和服务扩展了 Context 类。因此它们可以直接用于访问上下文。

Context is Instances of the the class android.content.Context provide the connection to the Android system which executes the application. For example, you can check the size of the current device display via the Context.

It also gives access to the resources of the project. It is the interface to global information about the application environment.

The Context class also provides access to Android services, e.g., the alarm manager to trigger time based events.

Activities and services extend the Context class. Therefore they can be directly used to access the Context.

爱*していゐ 2024-10-10 15:47:23

上下文是应用程序/对象当前状态的上下文。它是表示各种环境数据的实体。 Context 帮助当前 Activity 与外部 Android 环境进行交互,例如本地文件、数据库、与环境关联的类加载器、包括系统级服务在内的服务等。

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

获取上下文的不同调用方法
1. 获取应用程序上下文(),
2. getContext(),
3. 获取BaseContext()
4. 或这个(在活动课上时)。

Context is context of current state of the application/object.Its an entity that represents various environment data . Context helps the current activity to interact with out side android environment like local files, databases, class loaders associated to the environment, services including system-level services, and more.

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. It’s like a handle to the environment your application is currently running in. The activity object inherits the Context object.

Different invoking methods by which you can get context
1. getApplicationContext(),
2. getContext(),
3. getBaseContext()
4. or this (when in the activity class).

素食主义者 2024-10-10 15:47:23

上下文基本上用于资源访问并获取应用程序(对于应用程序上下文)或活动(对于活动上下文)或任何其他的环境详细信息...

为了避免内存泄漏,您应该为每个需要上下文的组件使用应用程序上下文对象....有关更多信息,请点击此处

Context is basically for resource access and getting the environment details of the application(for application context) or activity (for activity context) or any other...

In order to avoid memory leak you should use application context for every components that needs a context object.... for more click here

花间憩 2024-10-10 15:47:23

简而言之,Android 的 Context 是一团糟,除非您不再担心,否则您不会喜欢它。

Android Context 是:

  • God-objects。

  • 当您开始为 Android 开发时,您希望传递所有应用程序,但当您更接近编程、测试和 Android 本身时,您会避免这样做。

    • 依赖关系不明确。

    • 内存泄漏的常见来源。

    • 用于测试的 PITA。

  • Android 系统用于调度权限、资源、首选项、服务、广播、样式、显示对话框和膨胀布局的实际上下文。对于某些单独的事情,您需要不同的 Context 实例(显然,您无法从应用程序或服务上下文中显示对话框;从应用程序和活动上下文中扩展的布局可能会有所不同)。

Putting simple, Androids Context is a mess that you won't love until you stop worrying about.

Android Contexts are:

  • God-objects.

  • Thing that you want to pass around all your application when you are starting developing for Android, but will avoid doing it when you get a little bit closer to programming, testing and Android itself.

    • Unclear dependency.

    • Common source of memory leaks.

    • PITA for testing.

  • Actual context used by Android system to dispatch permissions, resources, preferences, services, broadcasts, styles, showing dialogs and inflating layout. And you need different Context instances for some separate things (obviously, you can't show a dialog from an application or service context; layouts inflated from application and activity contexts may differ).

缺⑴份安定 2024-10-10 15:47:23

上下文意味着 Android 知道我应该进行或执行哪个活动。

1 - Toast.makeText(context, "Enter All Details", Toast.LENGTH_SHORT).show();
它用于此。
Context context = ActivityName.this;

2 -startActivity(new Intent(context,LoginActivity.class));

在此上下文中表示您想要从哪个活动转到其他活动。
context 或 ActivityName.this 比 getContext 和 getApplicatinContext 更快。

Context means Android get to know in which activity I should go for or act in.

1 - Toast.makeText(context, "Enter All Details", Toast.LENGTH_SHORT).show();
it used in this.
Context context = ActivityName.this;

2 -startActivity(new Intent(context,LoginActivity.class));

in this context means from which activity you wanna go to other activity.
context or ActivityName.this is faster then , getContext and getApplicatinContext.

会傲 2024-10-10 15:47:23

老板助理类比

在深入了解上下文的技术细节之前,让我们先做一个小类比

每个老板都有一个助理或一个做事较少的人(跑腿的人)
对他来说重要且更耗时的事情。例如,如果他们
需要文件或咖啡,然后助理就会开始工作。老板不会
知道后台发生了什么,但文件或任务会
已交付

所以在这里
Boss - Android 应用程序
助理 - 上下文
文件或一杯咖啡 - 资源

Android 开发者官方网站对 Context

上下文是应用程序相关资源的访问点

让我们看看一些此类资源或任务

  • 启动活动。

  • 获取文件系统上特定于应用程序的缓存目录的绝对路径。

  • 确定给定权限是否允许用于系统中运行的特定进程和用户 ID。

  • 检查您是否已被授予特定权限。

等等。
因此,如果 Android 应用程序想要启动一个 Activity,它会直接进入 Context(访问点),而 Context 类会返回给他资源(在本例中为 Intent) 。

与任何其他类一样,Context 类也有字段和方法。
您可以在官方文档中探索有关 Context 的更多信息,它涵盖了几乎所有内容,可用的方法、字段,甚至如何将字段与方法一起使用。

Boss Assistant Analogy

Let's have a small analogy before diving deep in the technicality of Context

Every Boss has an assistant or someone( errand boy) who does less
important and more time-consuming things for him. For example, if they
need a file or coffee then an assistant will be on run. Boss will not
know what is going on in the background but the file or the task will
be delivered

So Here
Boss - Android Application
Assistant - Context
File or cup of coffee - Resource

What official Android Developer site says about Context

Context is your access point for application-related resources

Let's see some of such resources or tasks

  • Launching an activity.

  • Getting an absolute path to the application-specific cache directory on the filesystem.

  • Determining whether the given permission is allowed for a particular process and user ID running in the system.

  • Checking whether you have been granted a particular permission.

And so on.
So if an Android application wants to start an activity, it goes straight to Context (Access Point), and the Context class gives him back the resources(Intent in this case).

Like any other class Context class has fields and methods.
You can explore more about Context in official documentation, it covers pretty much everything, available methods, fields, and even how to use fields with methods.

小傻瓜 2024-10-10 15:47:23

Context 就是我们大多数人所说的应用程序。它由 Android 系统制作,只能完成应用程序能够完成的任务。
在 Tomcat 中,上下文也是我所说的应用程序。

一个Context可以容纳多个Activity,每个Activity可能有多个View。

显然,有些人会说它不适合,因为这样或那样,他们可能是对的,但是说 Context 是您当前的应用程序将帮助您理解您在方法参数中放入的内容。

A Context is what most of us would call Application. It's made by the Android system and is able to do only what an application is able to.
In Tomcat, a Context is also what I would call an application.

There is one Context that holds many Activities, each Activity may have many Views.

Obviously, some will say that it doesn't fit because of this or that and they are probably right, but saying that a Context is your current application will help you to understand what you are putting in method parameters.

能否归途做我良人 2024-10-10 15:47:23

Context 是每个应用程序的 Android 特定 api Sandbox
它提供对资源、数据库、私有文件目录、首选项、设置等应用程序私有数据的访问...

大多数私有数据对于一个应用程序的所有活动/服务/广播监听器都是相同的。

由于应用程序、活动、服务实现了 Context 接口,因此它们可以在 api 调用需要 Context 参数的情况下使用

The Context is the android specific api to each app-s Sandbox
that provides access app private data like to resources, database, private filedirectories, preferences, settings ...

Most of the privatedata are the same for all activities/services/broadcastlisteners of one application.

Since Application, Activity, Service implement the Context interface they can be used where an api call needs a Context parameter

流心雨 2024-10-10 15:47:23

android.content.Context 类的实例提供与执行应用程序的 Android 系统的连接。例如,您可以通过 Context 检查当前设备显示的大小。

它还允许访问项目的资源。它是有关应用程序环境的全局信息的接口。

Context 类还提供对 Android 服务的访问,例如,警报管理器以触发基于时间的事件。

活动和服务扩展了 Context 类。因此它们可以直接用于访问上下文。

Instances of the the class android.content.Context provide the connection to the Android system which executes the application. For example, you can check the size of the current device display via the Context.

It also gives access to the resources of the project. It is the interface to global information about the application environment.

The Context class also provides access to Android services, e.g., the alarm manager to trigger time based events.

Activities and services extend the Context class. Therefore they can be directly used to access the Context.

再见回来 2024-10-10 15:47:23

如果您想将 Context 与 Android 中其他熟悉的类连接,请记住以下结构:

上下文<上下文包装器应用

上下文<上下文包装器ContextThemeWrapper <<活动

上下文<上下文包装器ContextThemeWrapper <<活动<
列表活动

上下文<上下文包装器服务

上下文<上下文包装器服务<意图服务

因此,所有这些类都以自己的方式构成上下文。如果您愿意,您可以将 ServiceListActivity 强制转换为 Context。但如果仔细观察,某些类也继承了主题。在活动或片段中,您希望将主题应用到您的视图,但不关心它的Service类。

我在此处解释了上下文中的差异。

If you want to connect Context with other familiar classes in Android, keep in mind this structure:

Context < ContextWrapper < Application

Context < ContextWrapper < ContextThemeWrapper < Activity

Context < ContextWrapper < ContextThemeWrapper < Activity <
ListActivity

Context < ContextWrapper < Service

Context < ContextWrapper < Service < IntentService

So, all of those classes are contexts in their own way. You can cast Service and ListActivity to Context if you wish. But if you look closely, some of the classes inherit theme as well. In activity or fragment, you would like theming to be applied to your views, but don't care about it Service class, for instance.

I explain the difference in contexts here.

动听の歌 2024-10-10 15:47:23

上下文是指各个时间段内的组件(或应用程序)。如果我在下午 1 点到 2 点之间确实吃了很多食物,那么我那段时间的上下文将用于访问我在那段时间使用的所有方法(或资源)。内容是特定时间的组件(应用程序)。应用程序组件的上下文根据组件或应用程序的底层生命周期不断变化。
例如,在 Activity 的 onCreate() 内部,

getBaseContext() - 给出 Activitycontext > 由 Activity 的构造函数设置(创建)。
getApplicationContext() -- 在创建应用程序期间提供(创建)Context 设置。

注意: 包含所有 Android 组件。

<application>
    <activity> .. </activity> 

    <service>  .. </service>

    <receiver> .. </receiver>

    <provider> .. </provider>
</application> 

这意味着,当您从任何组件内部调用 getApplicationContext() 时,您正在调用整个应用程序的公共上下文。

Context 系统根据组件的生命周期不断修改。

Context means component (or application) in various time-period. If I do eat so much food between 1 to 2 pm then my context of that time is used to access all methods (or resources) that I use during that time. Content is a component (application) for a particular time. The Context of components of the application keeps changing based on the underlying lifecycle of the components or application.
For instance, inside the onCreate() of an Activity,

getBaseContext() -- gives the context of the Activity that is set (created) by the constructor of activity.
getApplicationContext() -- gives the Context setup (created) during the creation of application.

Note: <application> holds all Android Components.

<application>
    <activity> .. </activity> 

    <service>  .. </service>

    <receiver> .. </receiver>

    <provider> .. </provider>
</application> 

It means, when you call getApplicationContext() from inside whatever component, you are calling the common context of the whole application.

Context keeps being modified by the system based on the lifecycle of components.

不打扰别人 2024-10-10 15:47:23

Context 到底是什么?

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

来自“Android 实践 ” 书,p. 60.

一些 Android API 需要 Context 作为参数

如果您查看各种 Android API,您会发现
请注意,其中许多将 android.content.Context 对象作为
范围。您还会看到,活动或服务通常用作
上下文。这是可行的,因为这两个类都是从Context 扩展而来的。

What's Context exactly?

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.

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

Several Android APIs require a Context as parameter

If you look through the various Android APIs, you’ll
notice that many of them take an android.content.Context object 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.

有关上下文的更多详细信息,请阅读 这篇文章。我将简要解释这一点。

如果你想知道什么是上下文,你必须知道它的作用......
例如,getContext() 是检索上下文的方法之一。在 getContext() 中,Context 与 Activity 及其生命周期相关联。我们可以将 Context 想象成位于 Activity 后面的层,并且只要 Activity 存在,它就会存在。当 Activity 死亡时,Context 也会死亡。该方法给出了活动的功能列表,例如:

Load Resource Values,
Layout Inflation,
Start an Activity,
Show a Dialog,
Start a Service,
Bind to a Service,
Send a Broadcast,
Register BroadcastReceiver.

现在想象一下:

上下文是一个位于其组件后面的层(接口)
(活动、应用程序……)和组件的生命周期,它提供了
访问应用程序支持的各种功能
环境和Android框架。

for more details about context, read this article. I will explain that briefly.

If you wanna know what is context you must know what it does...
for example getContext() is one of the methods that retrieve context. In getContext(), Context is tied to an Activity and its lifecycle. We can imagine Context as layer which stands behind Activity and it will live as long as Activity lives. The moment the Activity dies, Context will too. this method gives list of functionalities to activity, like:

Load Resource Values,
Layout Inflation,
Start an Activity,
Show a Dialog,
Start a Service,
Bind to a Service,
Send a Broadcast,
Register BroadcastReceiver.

now imagine that :

Context is a layer(interface) which stands behind its component
(Activity, Application…) and component’s lifecycle, which provides
access to various functionalities which are supported by application
environment and Android framework.

落花浅忆 2024-10-10 15:47:23

如果你查看 https://stackoverflow.com/a/16301475/1772898 的评论,你会发现一条评论通过 ulf-edholm

嗯,对我来说,这一切听起来就像我们老前辈所说的全局变量,当面向对象进入场景时,这引起了人们的不满

。他是对的。上下文是全局变量的替代方案。

为了简单起见,我们可以这样说: 全局变量 ≈ 上下文 上下文

相对于全局变量的好处是,全局变量使得不可能在同一进程中创建同一系统的两个独立实例,而上下文允许系统的多个实例共存于一个进程中,每个实例都有自己的上下文。

请查看 John Ousterhout 的《软件设计哲学》,7.5 传递变量。

全局变量使得无法创建两个独立的
同一进程中同一系统的实例,因为访问
全局变量会发生冲突

...

我最常使用的解决方案是引入一个上下文对象,如下所示
图 7.2(d)。上下文存储应用程序的所有全局状态
(任何可能是传递变量或全局变量的东西
变量
)。大多数应用程序在其全局中都有多个变量
状态,表示配置选项、共享等内容
子系统和性能计数器。每个对象有一个上下文对象
系统的实例。 上下文允许多个实例
系统共存于单个进程中,每个进程都有自己的上下文

稍后在评论部分,您会发现 bjornw 的另一条评论

如果你只是 grep 一个代码库,你会看到数百个不同的 getContext、getBaseContext、getBlaBlaContext。

他也是对的。

为了减少必须了解上下文的方法的数量,在许多主要对象中引用了对上下文的引用。这就是为什么你在很多地方看到 getContext、getBaseContext、getBlaBlaContext ..。

参考:John Ousterhout 的《软件设计哲学》,7.5 传递变量。

不幸的是,很多地方可能都需要上下文,所以
它有可能成为传递变量。 减少
必须知道的方法数量,对上下文的引用
可以保存在系统的大部分主要对象中。在示例中
图7.2(d),包含m3的类存储了对
context 作为其对象中的实例变量。当一个新对象被
创建后,创建方法从其检索上下文引用
对象并将其传递给新对象的构造函数。有了这个
方法,上下文随处可用,但仅显示为
构造函数中的显式参数。


If you look at the comment of https://stackoverflow.com/a/16301475/1772898 , you will find a comment by ulf-edholm

Hmmm, to me it all sounds like what we old timers used to call global variables, which was much frowned on when object orientation entered the scene

He is right. Context is an alternative to global variable.

For simplicity we can say that: global variable ≈ context

The benefit of context over global variable is, global variables make it impossible to create two independent instances of the same system in the same process, whereas, The context allows multiple instances of the system to coexist in a single process, each with its own context.

Please check A Philosophy of Software Design by John Ousterhout, 7.5 Pass-through variables.

global variables make it impossible to create two independent
instances of the same system in the same process, since accesses to
the global variables will conflict
.

...

The solution I use most often is to introduce a context object as in
Figure 7.2(d). A context stores all of the application’s global state
(anything that would otherwise be a pass-through variable or global
variable
). Most applications have multiple variables in their global
state, representing things such as configuration options, shared
subsystems, and performance counters. There is one context object per
instance of the system. The context allows multiple instances of the
system to coexist in a single process, each with its own context
.

later in the comment section, you will find another comment by bjornw

If you just grep a codebase you'll see hundreds of different getContext, getBaseContext, getBlaBlaContext.

He is also right.

To reduce the number of methods that must be aware of the context, a reference to the context is referred in many major objects. That is why you see getContext, getBaseContext, getBlaBlaContext .. in so many places.

Reference: A Philosophy of Software Design by John Ousterhout, 7.5 Pass-through variables.

Unfortunately, the context will probably be needed in many places, so
it can potentially become a pass-through variable. To reduce the
number of methods that must be aware of it, a reference to the context
can be saved in most of the system’s major objects
. In the example of
Figure 7.2(d), the class containing m3 stores a reference to the
context as an instance variable in its objects. When a new object is
created, the creating method retrieves the context reference from its
object and passes it to the constructor for the new object. With this
approach, the context is available everywhere, but it only appears as
an explicit argument in constructors.

情话已封尘 2024-10-10 15:47:23

将 Context 视为一个包含不同资源的盒子:字符串、颜色和字体。如果您需要资源,请转到此框。当您旋转屏幕时,此框会发生变化,因为方向会变为横向。

Think of Context as a box with different resources: string, colors, and fonts. If you need a resource, you turn to this box. When you rotate the screen, this box changes because the orientation changes to landscape.

む无字情书 2024-10-10 15:47:23

另一个类比:

Context 可以被认为是办公室钥匙卡。
您必须随身携带它才能进入某些限制区域。
在 Android 中,这包括:系统服务、应用程序文件、资产、主题、权限等。

在实践中,Context 由应用程序组件表示(例如 ActivityActivityActivity >服务)。就像不同的钥匙卡可以解锁某些门但不能解锁其他门一样,某些应用程序组件作为上下文的用途有限(例如,您不能使用它来启动对话框或膨胀布局)。

Another analogy:

Context can be thought of as an office keycard.
You must carry it around in order to gain access to certain restricted areas.
In Android this includes: system services, application's files, assets, themes, permissions, etc.

In practice, a Context is represented by an application component (e.g. Activity, Service). And just like different keycards can unlock some of the doors but not others, some application components have limited usage as a Context (e.g. you can't use it to launch a dialog or inflate a layout).

醉生梦死 2024-10-10 15:47:22

简而言之:

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

您可以通过调用 getApplicationContext()getContext()getBaseContext()this 来获取上下文(当在从 Context 扩展的类中,例如 Application、Activity、Service 和 IntentService 类)。

上下文的典型用途:

  • 创建新对象
    创建新的视图、适配器、侦听器:

     TextView tv = new TextView(getContext());
     ListAdapter 适配器 = new SimpleCursorAdapter(getApplicationContext(), ...);
    
  • 访问标准公共资源
    LAYOUT_INFLATER_SERVICE、SharedPreferences 等服务:

     context.getSystemService(LAYOUT_INFLATER_SERVICE)
     getApplicationContext().getSharedPreferences(*名称*, *模式*);
    
  • 隐式访问组件
    关于内容提供商、广播、意图

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

Putting it simply:

As the name suggests, it's the context of the 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).

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, ...);
    
起风了 2024-10-10 15:47:22

上下文的定义

  • 上下文代表环境数据
  • 它提供对数据库等事物的访问

更简单的术语(示例 1)

  • 假设 Person-X 是一家初创公司的首席执行官软件公司。

  • 公司中有一位首席架构师,这位首席架构师
    完成公司中涉及数据库、UI 的所有工作
    等等

  • 现在首席执行官已经聘请了一位新开发人员。

  • 是建筑师告诉新员工的责任
    根据新人的技能以及他是否愿意
    从事数据库或用户界面等工作。

更简单的术语(示例 2)

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

  • 这类似于您访问酒店时,您想要早餐、午餐和晚餐。
    在合适的时间吃晚饭,对吗?

  • 入住期间还有很多其他您喜欢的事情。你如何获得这些东西?

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

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


涉及上下文的事情有:

  1. 加载资源。
  2. 启动新活动。
  3. 创建视图。
  4. 获取系统服务。

上下文是ActivityServiceApplication等的基类

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

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

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


获取上下文的不同方法

  • getApplicationContext()
  • getContext()
  • getBaseContext()
  • this (在活动类中时)

示例:< /em>

TextView tv = new TextView(this);

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

Definition of Context

  • Context represents environment data
  • It provides access to things such as databases

Simpler terms (example 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 database, UI
    etc.

  • Now the CEO has hired a new Developer.

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

Simpler terms (example 2)

  • It's like access to Android activity to the app's resources.

  • 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, and finally the breakfast, lunch &
    dinner has to be the resource.


Things that involve context are:

  1. Loading a resource.
  2. Launching a new activity.
  3. Creating views.
  4. obtaining system service.

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

Another way to describe this: Consider context as remote of a TV & channels in the television are resources, services, using intents, etc - - - Here remote acts as an access to get access to all the different resources in the 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


Different methods by which you can get context

  • getApplicationContext()
  • getContext()
  • getBaseContext()
  • or this (when in the activity class)

Example:

TextView tv = new TextView(this);

The keyword this refers to the context of the current activity.

流绪微梦 2024-10-10 15:47:22

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

如需了解更多信息,请参阅使用 Android Studio 进行 Android 开发简介 - 教程< /a>。

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.

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

流年里的时光 2024-10-10 15:47:22

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

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

在下图中,您可以看到类的层次结构,其中 < code>Context 是该层次结构的根类。特别值得强调的是,ActivityContext 的后代。

活动图

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

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 Context is the root class of this hierarchy. In particular, it's worth emphasizing that Activity is a descendant of Context.

Activity diagram

栀子花开つ 2024-10-10 15:47:22

Context 到底是什么?

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

来自“Android 实践”布克页。 60.

一些 Android API 需要 Context 作为参数

如果您查看各种 Android API,您会发现
请注意,其中许多将 android.content.Context 对象作为
范围。您还会看到,活动或服务通常用作
上下文。这是可行的,因为这两个类都是从Context 扩展而来的。

What's Context exactly?

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.

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

Several Android APIs require a Context as parameter

If you look through the various Android APIs, you’ll
notice that many of them take an android.content.Context object 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.

翻身的咸鱼 2024-10-10 15:47:22

理解android中的上下文的简单示例:

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

在这种情况下,

Boss - 是 Android 应用程序

Assistant - 是上下文

文件/一杯咖啡 - 是资源

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

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

  • 加载公共资源
  • 创建动态视图
  • 显示Toast消息
  • 启动活动等

获取上下文的不同方式:

getContext()

getBaseContext()

getApplicationContext()

this

Simple Example to understand context in 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

Assistant – is a 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.

Different ways of getting context:

getContext()

getBaseContext()

getApplicationContext()

this
晨光如昨 2024-10-10 15:47:22

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

如果您的 Android 应用程序是一个 Web 应用程序,您的上下文将类似于 ServletContext(我不会在这里进行精确比较)。

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

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

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

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

把梦留给海 2024-10-10 15:47:22
  • Context 表示获取环境数据的句柄。
  • Context 类本身被声明为抽象类,其实现由 android 操作系统提供。
  • Context 就像电视和电视的遥控器一样。电视中的频道是资源、服务等。
    输入图像描述这里

你能用它做什么?

  • 正在加载资源。
  • 开展新活动。
  • 创建视图。
  • 获取系统服务。

获取上下文的方法:

  • getApplicationContext()
  • getContext()
  • getBaseContext()在此处输入图像描述在此处输入图像描述
  • Context represents a handle to get environment data .
  • Context class itself is declared as abstract, whose implementation is provided by the android OS.
  • Context is like remote of a TV & channel's in the television are resources, services, etc.
    enter image description here

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文