【问题标题】:Automatically disconnect GoogleApiClient自动断开 GoogleApiClient
【发布时间】:2016-08-04 04:46:33
【问题描述】:

我想为GoogleApiClient 编写一个包装器,以便在活动的onDestroy 方法期间自动断开连接,如果它没有显式关闭。这样做的主要动机是通过忘记在使用 Activity 上下文创建的 GoogleApiClient 上调用 disconnect() 来避免内存泄漏。我想在整个应用程序中使用这个包装器。

我想知道是否有任何建议支持或反对这种创建自动关闭连接的设计决策?

【问题讨论】:

    标签: android google-api-client


    【解决方案1】:

    提供了答案,但不是最佳解决方案,也没有直接回答问题。问题是如何自动管理 GoogleApiClient。有一个名为enableAutoManage() 的选项。

    文档:https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient.Builder

    您可以通过以下方式启用此功能:

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this) //auto manage disconnecting client
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                .build();
    

    此外,onPause() 不是断开客户端连接的最佳位置。您应该使用 onStop()。尤其是现在,因为它保证被称为 post-Honeycomb 设备(API 11 +)

    @Override
    protected void onStop() {
        super.onStop();
        // stop GoogleApiClient
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }
    

    希望这会有所帮助。干杯!

    【讨论】:

      【解决方案2】:

      只要做:`

      @Override
      protected void onPause() {
          super.onPause();
      
          // Your application logic
          // ...
          // ...
      
          mGoogleApiClient.disconnect();
      }
      

      像往常一样,只是不要忘记在其中包含 mGoogleApiClient.disconnect(),而不是在 onDestroy() 上,因为这不是 Google 实施的生命周期(或至少尝试推荐,在您的情况下),您仍然需要在onStart() 上调用客户端连接。这个解决方案只有一行代码

      【讨论】:

        猜你喜欢
        • 2016-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-26
        • 1970-01-01
        • 2013-08-02
        相关资源
        最近更新 更多