Android中的Context详解
Context字面意思上下文,位于framework package的android.content.Context中,其实该类为LONG型,类似Win32中的Handle句柄,很多方法需要通过 Context才能识别调用者的实例。Context更像是一个父节点的实例,通过获取Context可以获取当前父节点的很多信息,1.public abstract Context getApplicationContext ()
Return the context of the single, global Application object of the current process.
返回一个应用中的父节点,这个父节点是全局唯一的,如果把一个Application当做一个树的话,这颗树中有各种各样的节点,那么这个方法就是获取根节点的信息。
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.获取一个ContentResolver实例,在Content Providers这个实例是属于一个Context用来共享数据的接口的数据成员。
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:
每个Application有一个Context,每个Activity是一个Context,对于一个Activity中的ViewGroup来说,当前的Acitivity就是他们的Context。如:TextView mTextView = new TextView(this);通过传递this传递信息到一个TextView实例中去,并可以获得Activity的信息,并且mTextView的生命随着Acitivity一起消亡。所以不能定义比Context生命周期还要长的数据,否侧会产生内存泄露。
浙公网安备 33010602011771号