在Android開發(fā)中湿硝,我們經(jīng)常會(huì)使用到Context對(duì)象薪前,Context即上下文環(huán)境,如當(dāng)我們想要輸出調(diào)試信息時(shí)关斜,經(jīng)常使用的
Toast.makeText(this,"Android小技巧-獲取全局Context", Toast.LENGTH_SHORT).show();
//public static Toast makeText(Context context, CharSequence text, @Duration int duration)
存在的問題
1.每次都需要傳入Context對(duì)象十分繁瑣示括;
2.一般是從Activity和Fragment等組件中獲取,當(dāng)方法脫離了它們后痢畜,無法獲取垛膝,需要傳入Context參數(shù),治標(biāo)不治本裁着。
3.傳統(tǒng)的做法限制了框架的發(fā)展繁涂,如無法將Toast方法封裝拱她,即?傳統(tǒng)的方法是
public static toast(Context context,String msg){
Toast.makeText(context,"Android小技巧-獲取全局Context", Toast.LENGTH_SHORT).show();
}
傳統(tǒng)的封裝方式把Context的來源交給了調(diào)用者二驰,未免有些不負(fù)責(zé)任,那么理想的方式是Toast只需關(guān)注要顯示的msg秉沼,無需關(guān)注context桶雀,即
public static toast(String msg){
Toast.makeText(全局Context,"Android小技巧-獲取全局Context", Toast.LENGTH_SHORT).show();
}
解決的方案
Android提供了一個(gè)Application類,每當(dāng)App啟動(dòng)時(shí)唬复,系統(tǒng)會(huì)將Application進(jìn)行初始化矗积,并存在于App的整個(gè)生命周期中。
細(xì)心的開發(fā)者會(huì)注意到敞咧,我們可以在Application內(nèi)對(duì)一些全局狀態(tài)的信息進(jìn)行管理棘捣,如Context、如Volley的RequestQueue休建、如Universal-Image-Loader的初始化乍恐。
那么评疗,在Application中,我們只需在程序啟動(dòng)時(shí)獲取一次Context茵烈,隨后需要Context的地方只需從Application中獲取即可百匆。
核心代碼如下:
//上下文
public static Context context;
public static Context getContext() { return context;}
@Overridepublic void onCreate() {
super.onCreate();
context = getApplicationContext();
}
整體代碼
public class App extends Application {
public static App app;//單例化Application
public static App getApp() {
if (app == null) {
synchronized (App.class) { //線程安全
if (app == null) {
app = new App();
}
}
}
return app;
}
//上下文
public static Context context;
public static Context getContext() { return context;}
@Overridepublic void onCreate() {
super.onCreate();
context = getApplicationContext();
}
}
當(dāng)然,別忘記了在AndroidManifest.xml中的Application標(biāo)簽添加
<application
android:name="包名.App"
....../>