Android中Context简介

AndroidContext简介

 

 

Context字面意思是上下文,位于framework packageandroid.content.Context中,其实该类为LONG型,类似Win32中的Handle句柄。很多方法需要通过 Context才能识别调用者的实例:比如说Toast的第一个参数就是Context,一般在Activity中我们直接用this代替,代表调用者的实例为Activity,而到了一个buttononClick(View view)等方法时,我们用this时就会报错,所以我们可能使用ActivityName.this来解决,主要原因是因为实现Context的类主要有Android特有的几个模型,Activity以及Service

Context提供了关于应用环境全局信息的接口。它是一个抽象类,它的执行被Android系统所提供。它允许获取以应用为特征的资源和类型。同时启动应用级的操作,如启动Activitybroadcasting和接收intents

下面介绍Context的一些get方法,通过这些get方法可以获取应用环境全局信息:

1.public abstract Context getApplicationContext ()

Return the context of the single, global Application object of the current process.

2.public abstract ApplicationInfo getApplicationInfo ()

Return the full application info for this context's package.

3.public abstract ContentResolver getContentResolver ()

Return a ContentResolver instance for your application's package.

4.public abstract PackageManager getPackageManager ()

Return PackageManager instance to find global package information.

5.public abstract String getPackageName ()

Return the name of this application's package.

6.public abstract Resources getResources ()

Return a Resources instance for your application's package.

7.public abstract SharedPreferences getSharedPreferences (String name, int mode)

Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.

8.public final String getString (int resId)

Return a localized string from the application's package's default string table.

9.public abstract Object getSystemService (String name)

Return the handle to a system-level service by name. The class of the returned object varies by the requested name. Currently available names are:

还有很多有用的方法,具体不一一列举。详情请参考文档,反正Context很有用。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android开发Context是一个重要的概念,它代表了Android应用程序的当前状态和环境。它提供了访问应用程序资源(如布局、字符串等)和执行各种操作(如启动Activity、访问数据库等)的能力。 数据库在Android开发也是非常常见的,它用于存储和管理应用程序的数据。Android提供了SQLite数据库来支持本地数据存储。要在应用程序使用数据库,首先需要创建一个数据库实例,并获取对数据库的读写访问权限。这就是我们需要Context的原因之一。 通过Context,我们可以获取应用程序的上下文环境,包括访问数据库所需的一些关键组件,如ContentResolver和SQLiteOpenHelper。ContentResolver是用于访问应用程序的数据提供者的类,而SQLiteOpenHelper则是一个辅助类,用于管理SQLite数据库的创建和版本控制。 使用Context来访问数据库时,可以通过调用getApplicationContext()方法获取全局的应用程序上下文,或者通过调用Activity的getContext()方法获取当前活动的上下文。这样就可以使用上述提到的组件来执行与数据库相关的操作,例如插入、查询、更新和删除数据等。 总结一下,ContextAndroid是一个重要的概念,它提供了访问应用程序资源和执行各种操作的能力。而数据库则是Android开发常用的数据存储方式,通过Context可以获取对数据库的读写访问权限,并使用相关组件来操作数据库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值