我的应用需要跟踪用户当前位置。我正在使用LocationServices FusedLocationApi这样做。问题是当用户安装我的应用并启动应用时,我的应用无法跟踪用户位置。这个问题只是第一次出现。然后,每当我的应用程序打开该活动,我没有遇到任何问题。我的应用程序能够跟踪用户位置。
@Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
Log.d(APP_TAG,"A");
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Display UI and wait for user interaction
} else {
// Check Permissions Now
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
}
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
//return;
}
//DevicePreferences.getGoogleApiClient().connect();
//LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
LocationServices.FusedLocationApi.getLocationAvailability(mGoogleApiClient);
/*mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);*/
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
Log.d(APP_TAG,""+mLastLocation);
/*while (mLastLocation == null){
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
}*/
if (mLastLocation != null) {
changeMap(mLastLocation);
Log.d(APP_TAG, "ON connected");
} else
try {
Log.d(APP_TAG, "B");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
/*LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);*/
} catch (Exception e) {
e.printStackTrace();
}
try {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000); //10000
mLocationRequest.setFastestInterval(1000); //5000
// mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(APP_TAG,"4");
mGoogleApiClient.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:1)
初始化您的 mGoogleApiClient ,如果您还没有,请执行以下操作:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
如果,还有其他任何问题,请详细描述,使用更多代码