我們都知道靜態存儲上下文對象(除了應用程序上下文)是不好的做法,因為它會導致內存泄漏。但是您可以存儲從上下文對象派生的系統服務嗎?比如ConnectivityManager?// Is this okay?static ConnectivityMananger connectivityManager;...connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
1 回答

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