当我在片段中调用onActivityResult时,我在父活动中拥有的GoogleApiClient"未连接"。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Constants.REQUEST_PLACE_PICKER) {
if (resultCode == Activity.RESULT_OK) {
/* User has picked a place, extract data.
Data is extracted from the returned intent by retrieving a Place object from
the PlacePicker.
*/
final Place place = PlacePicker.getPlace(data, getActivity());
SharedPreferences prefs = getActivity().getSharedPreferences(Constants.SHARED_PREFS, Context.MODE_MULTI_PROCESS);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("address"+id, address.toString()).commit();
editor.putString("name"+id, name.toString()).commit();
Log.d(TAG, "Just picked a location, id=" + id);
((AllinOneActivity getActivity()).addGeofenceFromListposition(id);
getActivity()).addGeofencesButtonHandler(); // <-- This code that checks mGoogleCLientApi.connected()
mRecyclerView.setAdapter(new LocationListAdapter(getGymLocations(), mListener, this));
} else {
Log.d(TAG, "resultCode is wrong " + "resultCode");
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
但是,如果我在同一片段类的按钮中执行相同的操作,则该内容已连接。
//in onCreateView
mFab = (FloatingActionButton) view.findViewById(R.id.fab);
mFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onListFragmentInteraction(); //<-- Work fine!
}
});
AFAIK 这应该调用相同的活动,那么为什么客户端在第一个中断开连接,而不是第二个?
//In parent Activity
public void onListFragmentInteraction(){
addGeofencesButtonHandler();
}
public void addGeofencesButtonHandler() {
Log.d(TAG, "Adding geoFencesButtonHandler click");
if (!mGoogleApiClient.isConnected()) {
Toast.makeText(this, "not connected in addgeofence", Toast.LENGTH_SHORT).show();
return;
}
try {
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
// The GeofenceRequest object.
getGeofencingRequest(),
// A pending intent that that is reused when calling removeGeofences(). This
// pending intent is used to generate an intent when a matched geofence
// transition is observed.
getGeofencePendingIntent()
).setResultCallback(this); // Result processed in onResult().
} catch (SecurityException securityException) {
// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
logSecurityException(securityException);
}
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
当您连接GoogleApiClient时,它不会立即连接。 您必须注册连接回调侦听器才能知道连接何时实际完成。
在您的情况下,发生的事情是 onActivityResult() 在您从 onStart() 的连接完成之前,Android 正在调用 onActivityResult()。 onActivityResult() 在 onStart() 和 onResume() 之间被调用,但你不能假设客户端连接在调用 onActivityResult() 时已经完成。
相反,您需要做的是在成员变量中记住onActivityResult()的结果,然后在连接侦听器中检查该值,以了解何时可以安全地将GoogleApiClient对象与该数据一起使用。
您是否在停止或销毁活动中断开了 api 的连接?