GoogleApiClient可以在片段中使用,还是必须始终在活动中使用?

kcu*_*ube 3 android

GoogleApiClient可以在片段中使用,还是必须始终在Activity中使用

mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
Run Code Online (Sandbox Code Playgroud)

Md.*_*rim 10

GoogleApiClient可以工作Activity,FragmentService.它需要Context你可以通过得到它getApplicationContext(),getActivity()等你Fragment/Activity需要实现这两个接口:

implements
ConnectionCallbacks, OnConnectionFailedListener
Run Code Online (Sandbox Code Playgroud)

然后你会发现这些方法:

@Override
public void onConnected(Bundle bundle) { 

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}
Run Code Online (Sandbox Code Playgroud)

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

以下是有关访问Google API的文档.是描述.而这个线程有我的演示工作代码.

  • 当在片段中使用时,`getActivity()`在包含片段的活动实现Callback之前不会起作用.相反,`fragment_name.this`或`this`将是获取片段中的上下文的正确方法,片段必须实现回调 (2认同)

Flo*_*ern 5

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

new GoogleApiClient.Builder(getActivity())
...
Run Code Online (Sandbox Code Playgroud)