【问题标题】:Can GoogleApiClient be used in a Fragment or must it be always used in a Activity?GoogleApiClient 可以在 Fragment 中使用还是必须始终在 Activity 中使用?
【发布时间】:2017-03-28 20:19:11
【问题描述】:

GoogleApiClient 可以在 Fragment 中使用还是必须始终在 Activity 中使用

mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

【问题讨论】:

    标签: android


    【解决方案1】:

    GoogleApiClient 可以在ActivityFragmentService 中工作。它需要一个Context,您可以通过getApplicationContext()getActivity() 等获得它。您的Fragment/Activity 必须实现这两个接口:

    implements
    ConnectionCallbacks, OnConnectionFailedListener
    

    然后你会发现这些方法:

    @Override
    public void onConnected(Bundle bundle) { 
    
    }
    
    @Override
    public void onConnectionSuspended(int i) {
    
    }
    
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    
    }
    

    您必须使用此mGoogleApiClient.connect(); 连接此 API 客户端并通过 mGoogleApiClient.disconnect() 断开连接

    Here 是有关访问 Google API 的文档。 Here 是描述。 this thread 有我的 Demo 工作代码。

    【讨论】:

    • 当在片段中使用时,getActivity() 在持有片段的活动实现回调之前将不起作用。相反,fragment_name.thisthis 将是在片段中获取上下文的正确方法,并且片段必须实现回调
    【解决方案2】:

    是的,您可以在片段中使用它。您只需向构建器提供一个上下文(您可以使用getActivity())并让片段实现所需的接口。

    new GoogleApiClient.Builder(getActivity())
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      • 2020-02-08
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      相关资源
      最近更新 更多