Google 客户端实现如下:
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
.addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
.addApi(LocationServices.API)
.build();
}
onStart 我正在连接谷歌Api客户端
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null)
mGoogleApiClient.connect();
}
直到这里一切都很好,但在连接的方法上它返回 null
@Override
public void onConnected(Bundle bundle) {
if (bundle != null)// always null
Log.e(TAG, bundle.toString());
}
获取位置代码在连接到谷歌 api 客户端后单击浮动按钮
//Floating Action Button
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onClick(View v) {
//To Check Runtime Permission
checkRuntimePermission();
mMap.clear();
mMap.setMyLocationEnabled(true);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(50);
mLocationRequest.setFastestInterval(10);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (!Utils.GPS_SERVICE(mContext)) {
Utils.isGPSOnline(mContext);
}
if (mLastLocation != null) {
double lon = mLastLocation.getLongitude();
double lat = mLastLocation.getLatitude();
LatLng latlng = new LatLng(lat, lon);
mMap.addMarker(new MarkerOptions().position(latlng).title("My_location"));
//TO move the marker when user enter any Location
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
}
尝试
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
.addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
.addApi(LocationServices.API)
.enableAutoManage(activityContext, this) // this - for implementing Interface
.build();
}
if (mGoogleApiClient == null)
也删除此条件并在回调中传递此条件
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
你也可以看看这个完整的例子 http://www.androidhive.info/2015/02/android-location-api-using-google-play-services/
如果onConnected()
被召唤,你GoogleApiClient
没关系。
为什么捆绑包为空?
看看这个方法——
public abstract void onConnected (Bundle connectionHint)
connectionHint
捆绑包的内容由特定服务定义。如果服务未提供任何内容,则可能为 null。