Android - GoogleApiClient - 没有连接片段的负载

时间:2018-04-26 03:56:06

标签: android android-fragments google-play-services

在片段onCreateview中,连接GoogleAPIClient,但它不会触发onConnected调用,但如果我转到另一个片段并返回则会触发它。

  

无法找到原因?任何帮助都会受到赞赏,因为我被卡住了?

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {   
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                    .enableAutoManage(getActivity(), GOOGLE_API_CLIENT_ID, this)
                    .addConnectionCallbacks(this)
                    .addApi(LocationServices.API)
                    .addApi(Places.GEO_DATA_API)
                    .addApi(Places.PLACE_DETECTION_API)
                    .build(); 
    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
    mPlaceArrayAdapter.setGoogleApiClient(mGoogleApiClient);
    Log.i(LOG_TAG, "Google Places API connected.");
 }

1 个答案:

答案 0 :(得分:2)

  

void onCreate (Bundle savedInstanceState)打算做首发   创建片段。

您应该添加 onCreate 部分

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

       mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                    .enableAutoManage(getActivity(), GOOGLE_API_CLIENT_ID, this)
                    .addConnectionCallbacks(this)
                    .addApi(LocationServices.API)
                    .addApi(Places.GEO_DATA_API)
                    .addApi(Places.PLACE_DETECTION_API)
                    .build(); 

        Log.d(TAG, "onCreate");
    }

然后

@Override
    public void onResume() {
        super.onResume();
        mGoogleApiClient .connect();
        Log.d(TAG, "onResume");
    }

检查 onPause() 状态是一种很好的方法。

@Override
    public void onPause() {
        super.onPause();
        if (mGoogleApiClient.isConnected())
            mGoogleApiClient.disconnect();
            Log.d(TAG, "onPause");
    }