前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android 中Context的使用方法详解

Android 中Context的使用方法详解

作者头像
砸漏
发布2020-10-22 10:11:03
7460
发布2020-10-22 10:11:03
举报
文章被收录于专栏:恩蓝脚本

Android 中Context的使用方法详解

概要:

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

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

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

代码语言:javascript
复制
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很有用。

如有疑问请留言或到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档