欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 中Context的使用方法详解

程序员文章站 2023-12-19 09:34:04
android 中context的使用方法详解 概要: context字面意思是上下文,位于framework package的android.content.cont...

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方法可以获取应用环境全局信息:

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很有用。

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

上一篇:

下一篇: