我們都知道靜態(tài)存儲(chǔ)上下文對(duì)象(除了應(yīng)用程序上下文)是不好的做法,因?yàn)樗鼤?huì)導(dǎo)致內(nèi)存泄漏。但是您可以存儲(chǔ)從上下文對(duì)象派生的系統(tǒng)服務(wù)嗎?比如ConnectivityManager?// Is this okay?static ConnectivityMananger connectivityManager;...connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
1 回答

慕沐林林
TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
我建議使用該應(yīng)用程序Context
來獲得這樣的系統(tǒng)服務(wù):
connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
可能所有系統(tǒng)服務(wù)都在Context
內(nèi)部使用該應(yīng)用程序,但這種方法更加安全,但需要額外的方法調(diào)用。
如果系統(tǒng)服務(wù)正在使用應(yīng)用程序,則在獲取系統(tǒng)服務(wù)時(shí)Context
不會(huì)泄露。Context
您是否通過使用系統(tǒng)服務(wù)泄漏任何其他內(nèi)容可能會(huì)有所不同。
添加回答
舉報(bào)
0/150
提交
取消