【问题标题】:How to handle GoogleApiClient on Fragments如何处理片段上的 GoogleApiClient
【发布时间】: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 对象时遇到了问题。调试我的应用程序时,我发现由于 FragmentView 的重新创建,内存中有两个不同的对象 mGoogleApiClient(在 muy ViewPager 中前进和后退)。

有没有办法处理GoogleApiClient 实例或连接本身?

提前致谢!

【问题讨论】:

    标签: android android-fragments google-play-services google-places-api google-api-client


    【解决方案1】:

    问题是,您误解了 Fragment 的用途 - 它只是 UI(以及 Activity)。不要把业务逻辑,比如取数据放在里面。创建单独的“模型”类,它将存储在应用程序(可能是活动)中并绑定到该应用程序(活动)的生命周期。通过一些接口 Activity implel 提供这些数据

    【讨论】:

    • 感谢您的回答,我赞成,因为您对这种方法的看法是正确的,但这并不能解决我的问题。
    猜你喜欢
    • 2014-03-19
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    相关资源
    最近更新 更多