Android中有个我们熟悉又陌生的对象Context(上下文),当我们启动Activity的时候需要上下文,当我们使用dialog的时候我们需要上下文,但是上下文对象到底是个什么东西呢?
在Android api当中是这样描述context对象的。
"Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc."
“是一个用于实现关于应用环境的整体信息的一个接口。这是一个由安卓系统提供的抽象类并且系统有对他进行实现。它允许访问到应用特殊的资源和类,同时它也可以实现到应用级别的操作,例如:Activity的启动,广播的实现和接受intent等。”
一、Context的主要实现和继续理解
Activity的继承关系:
Service和Application的继承关系:
二、Context中的主要方法
| abstract void |
startActivity(
Intent intent)
Same as
startActivity(Intent, Bundle) with no options specified.
|
| abstract void |
startActivity(
Intent intent,
Bundle options)
Launch a new activity.
|
| abstract Resources |
getResources()
Return a Resources instance for your application's package.
|
| 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.
|
| final String |
getString(int resId)
Return a localized string from the application's package's default string table.
|
| final String |
getString(int resId,
Object... formatArgs)
Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in
Formatter and
format(String, Object...).
|
| abstract ComponentName |
startService(
Intent service)
Request that a given application service be started.
|
| abstract boolean |
stopService(
Intent service)
Request that a given application service be stopped.
|
public static Toast makeText(Context context, CharSequence text, int duration) {
Toast result = new Toast(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
result.mNextView = v;
result.mDuration = duration;
return result;
}
可以看到makeText方法接受的context被用于
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
这是用于获取XML中定义的View的方法,可以看到通过外部传入的Context,在这里获得了一个View布局用于显示Toast。
public Toast(Context context) {
mContext = context;
mTN = new TN();
mTN.mY = context.getResources().getDimensionPixelSize(
com.android.internal.R.dimen.toast_y_offset);
mTN.mGravity = context.getResources().getInteger(
com.android.internal.R.integer.config_toastDefaultGravity);
}
这一行中可以看出在context又被用来获取资源文件,可以看出Toast的显示和布局都是通过context去调用系统写好的资源文件来进行实现的。
3066




被折叠的 条评论
为什么被折叠?



