我想寫一個GoogleApiClient
的包裝,在活動的onDestroy
方法中自動斷開連接,如果它沒有明確關閉。主要動機是通過忘記在使用Activity上下文創建的GoogleApiClient上調用disconnect()
來避免內存泄漏。我想在整個應用程序中使用這個包裝器。自動斷開GoogleApiClient
我想知道是否有任何建議支持或反對這種設計決策創建自動關閉連接?
我想寫一個GoogleApiClient
的包裝,在活動的onDestroy
方法中自動斷開連接,如果它沒有明確關閉。主要動機是通過忘記在使用Activity上下文創建的GoogleApiClient上調用disconnect()
來避免內存泄漏。我想在整個應用程序中使用這個包裝器。自動斷開GoogleApiClient
我想知道是否有任何建議支持或反對這種設計決策創建自動關閉連接?
只是做:`
@Override
protected void onPause() {
super.onPause();
// Your application logic
// ...
// ...
mGoogleApiClient.disconnect();
}
爲定期,只是不要忘了包括mGoogleApiClient.disconnect()
在那裏,而不是onDestroy()
因爲這不是,谷歌工具(或至少試圖推薦生命週期,在你的情況下),你仍然需要撥打onStart()
上的客戶端連接。此解決方案只是一行代碼長
提供了一個答案,但它不是最佳解決方案,也不直接回答問題。問題是如何自動管理GoogleApiClient。有一個選項叫做enableAutoManage()
。
您可以啓用此執行以下操作:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this) //auto manage disconnecting client
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
此外,在onPause()是不要斷開你的客戶的最佳場所。你應該使用onStop()。特別是現在,它被稱爲後蜂窩設備(API 11 +)保證保證
@Override
protected void onStop() {
super.onStop();
// stop GoogleApiClient
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
希望這是有幫助的。乾杯!