【发布时间】:2016-11-22 10:48:38
【问题描述】:
我有一个ViewPager,其中包含各种Fragments。在其中一个中,我调用 Google Places Api 来根据我的输入检索一些数据。后来我去下一个Fragment的时候,如果想回到上一个Fragment(引入另外一个输入),就检索不到数据了。
代码如下:
@Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
public void onStop() {
if(mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.my_fragment_layout, container, false);
mGoogleApiClient = new GoogleApiClient
.Builder(getActivity().getApplicationContext())
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
/* init my components */
Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId)
.setResultCallback(new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(@NonNull PlaceBuffer buffer) {
/* do my stuff */
}
});
return v;
}
我的问题是,当我从下一个 Fragment 返回并立即插入另一个输入时,我无法到达 onResult,因为 mGoogleApiClient 在获得回调结果之前断开连接。我必须插入两次才能使其工作。
我猜我在 Fragment 的生命周期中处理我的 mGoogleApiClient 对象时遇到了问题。调试我的应用程序时,我发现由于 Fragment 的 View 的重新创建,内存中有两个不同的对象 mGoogleApiClient(在 muy ViewPager 中前进和后退)。
有没有办法处理GoogleApiClient 实例或连接本身?
提前致谢!
【问题讨论】:
标签: android android-fragments google-play-services google-places-api google-api-client