關於android中的Context

2021-10-02 02:23:16 字數 1566 閱讀 3775

提到android,我們首先想到的是activity,service,broadcastreceiver,contentprovider,然而在使用這些元件的時候,卻離不開context今天就來研究一下context。

1.context是什麼

2.context裡面有哪些資料

3.context能提供什麼操作

context提供的操作多達上百個,主要是子類是contextimpl來實現的,這裡簡單提幾個常用的方法。

(2)public void settheme(int resid);設定主題

(3)public string getpackagename();獲取包名

(4)public sharedpreferences getsharedpreferences(string name, int mode);獲取sharedpreferences,非常輕量級的資料,如開關等。

(5)public fileinputstream openfileinput(string name)

public fileoutputstream openfileoutput(string name, int mode)檔案的輸入輸出流

(6)public file getexternalfilesdir(string type)獲取外部儲存路徑

(7)public sqlitedatabase openorcreatedatabase(string name, int mode, curso***ctory factory)建立sqlite資料庫。當然還有其他sqlite資料庫相關的函式.

(8)public void startactivity(intent intent)啟動乙個activity。

(10)public intent registerreceiver(broadcastreceiver receiver, intentfilter filter) 註冊廣播,當然別忘了呼叫public void unregisterreceiver(broadcastreceiver receiver),否則會導致廣播洩露。

(11)public componentname startservice(intent service)啟動乙個服務,成對的有public boolean stopservice(intent service)。

(12)public boolean bindservice(intent service, serviceconnection conn,

int flags)繫結的方式啟動服務,與服務通訊,成對的有public void unbindservice(serviceconnection conn)

(13)public object getsystemservice(string name)獲取系統服務,例如可以借助它來獲取wifimanager, connectivitymanager這些系統服務。

(15)public display getdisplay()獲取顯示相關的資訊。

4.如何獲取乙個context物件

(3)對於廣播,沒有context物件就無法使用

(4)對於contentprovider一般會有自己的方法去獲取context。

Android程式中任意位置獲取Context

context物件在android中是乙個很重要的內容,activity中我們很容易獲得該物件,然後在service以及其他class中並不是那麼簡單。下文介紹如何在任意位置獲得context物件。return instance override public void oncreate 這裡寫上完...

Android原始碼分析 全面理解Context

context是乙個抽象基類,我們通過它訪問當前包的資源 getresources getassets 和啟動其他元件 activity service broadcast 以及得到各種服務 getsystemservice 當然,通過context能得到的不僅僅只有上述這些內容。對context的...

關於android中的ANR

在onupdate中獲取到fields的更新值 final string fields new string 5 fields 0 notifyvalue update,x1 fields 1 notifyvalue update,x2 fields 2 notifyvalue update,x3 ...