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。 php
Context提供了關於應用環境全局信息的接口。它是一個抽象類,它的執行被Android系統所提供。它容許獲取以應用爲特徵的資源和類型。同時啓動應用級的操做,如啓動Activity,broadcasting和接收intents。 html
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方法能夠獲取應用環境全局信息: app
Return the context of the single, global Application object of the current process. ide
Return the full application info for this context's package. ui
Return a ContentResolver instance for your application's package. this
Return PackageManager instance to find global package information. url
Return the name of this application's package. spa
Return a Resources instance for your application's package. .net
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.
Return a localized string from the application's package's default string table.
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:
參考博客:http://blog.chinaunix.net/space.php?uid=17102734&do=blog&id=2830227