分类: Android平台
2012-07-18 17:44:57
转自:http://blog.csdn.net/ihrthk/article/details/7321309
Context字面意思上下文,Android中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以及BroadcastReceiver。
Context提供了关于应用环境全局信息的接口。它是一个抽象类,它的执行被Android系统所提供。它允许获取以应用为特征的资源和类型。同时启动应用级的操作,如启动Activity,broadcasting和接收intents。
protected void onCreate(Bundle state) {
super.onCreate(state); TextView label = new TextView(this);
//传递context给view control
label.setText("Leaks are bad"); setContentView(label); } |
public class myactivity extends Activity {
private static Drawable sBackground; protected void onCreate(Bundle state) { super.onCreate(state); TextView label = new TextView(this); label.setText("Leaks are bad"); if (sBackground == null) { sBackground = getDrawable(R.drawable.large_bitmap); } label.setBackgroundDrawable(sBackground);//drawable attached to a view setContentView(label); } } |
class MyApp extends Application { |
下面介绍Context的一些get方法,通过这些get方法可以获取应用环境全局信息:
Return the context of the single, global Application object of the current process.
Return the full application info for this context's package.
Return a ContentResolver instance for your application's package.
Return PackageManager instance to find global package information.
Return the name of this application's package.
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