在Android编程中,Context类到底是什么?它用于什么?
我在开发者网站上读过这篇文章,但我无法清楚地理解它。
在Android编程中,Context类到底是什么?它用于什么?
我在开发者网站上读过这篇文章,但我无法清楚地理解它。
当前回答
上下文表示当前。用于对当前屏幕执行操作的上下文。前任。 1. getApplicationContext() 2. 获取上下文()
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_SHORT).show();
其他回答
上下文表示获取环境数据的句柄。上下文类本身声明为抽象类,其实现由android OS提供。上下文就像电视的远程&电视中的频道是资源、服务等。
你能用它做什么?
正在加载资源。启动新活动。创建视图。正在获取系统服务。
获取上下文的方法:
getApplicationContext()获取上下文()getBaseContext()
上下文基本上用于资源访问和获取应用程序(用于应用程序上下文)或活动(用于活动上下文)或任何其他的环境详细信息。。。
为了避免内存泄漏,您应该为每个需要上下文对象的组件使用应用程序上下文。。。。有关详细信息,请单击此处
Context是android.content类的实例。Context提供到执行应用程序的android系统的连接。例如,您可以通过上下文检查当前设备显示的大小。
它还允许访问项目的资源。它是有关应用程序环境的全局信息的接口。
Context类还提供对Android服务的访问,例如报警管理器以触发基于时间的事件。
活动和服务扩展了Context类。因此,它们可以直接用于访问上下文。
简单地说:
顾名思义,它是应用程序/对象当前状态的上下文。它让新创建的对象了解发生了什么。通常,您调用它来获取有关程序的另一部分(活动和包/应用程序)的信息。
您可以通过调用getApplicationContext()、getContext()和getBaseContext()或this(当在从context扩展的类中时,例如Application、Activity、Service和IntentService类)来获取上下文。
上下文的典型用法:
创建新对象:创建新视图、适配器和侦听器:TextView tv=新建TextView(getContext());ListAdapter适配器=新的SimpleCursorAdapter(getApplicationContext(),…);访问标准公共资源:服务,如LAYOUT_INFLATER_SERVICE、SharedPreferences:context.getSystemService(LAYOUT_INFLATER_SERVICE)getApplicationContext().getSharedPreferences(*name*,*mode*);隐式访问组件:关于内容提供商、广播、意图getApplicationContext().getContentResolver().query(uri,…);
上下文是有关应用程序环境的全局信息的接口。这是一个抽象类,其实现由Android系统提供。
上下文允许访问特定于应用程序的资源和类,以及调用应用程序级操作,如启动活动、广播和接收意图等。
以下是示例
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