Android Context

来源:互联网 发布:vb窗体透明控件不透明 编辑:程序博客网 时间:2024/05/29 12:19

在android中context可以作很多操作,但是最主要的功能是加载和访问资源。

在android中有两种context,一种是 application context,一种是activity context,通常我们在各种类和方法间传递的是activity context。

避免context相关的内存泄露,记住以下几点:

1. 不要让生命周期长的对象引用activity context,即保证引用activity的对象要与activity本身生命周期是一样的

2. 对于生命周期长的对象,可以使用application context

3. 避免非静态的内部类,尽量使用静态类,避免生命周期问题,注意内部类对外部对象引用导致的生命周期变化

通常情况下获取当前应用的context的方法是getApplicationContext,但是通过根据其他的packageName构造 Context如代码

try {  

Context ctx= createPackageContext("com.android123.Cwj", 0); //ctx已经是com.android123.cwj的实例 }  

catch (NameNotFoundException e) {  

//可能由于 pacakgeName不存在所以必须处理该异常  

}

需要注意的是,createPackageContext方法的第二个参数可选为CONTEXT_INCLUDE_CODE 和 CONTEXT_IGNORE_SECURITY ,定义分别为4和2,上面为0。一般忽略安全错误问题可以通过CONTEXT_IGNORE_SECURITY 标记,同时可能还需要处理 SecurityException 异常.

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:


原创粉丝点击