安卓系统-我的应用程序可以在打开谷歌地图之前获得位置信息,尽管它有相关权限



我是Android开发的新手。所以我的问题可能太基本了。很抱歉。现在我正在维护以前编写的代码。

此应用程序使用手机的定位服务。在清单文件中写道:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

但是,尽管用户允许使用定位服务,但在大多数情况下,通过应用程序无法直接获得位置。

例如,当我的应用程序无法获取位置信息时,打开谷歌地图应用程序后,我的应用软件总是可以获取位置信息。那么我对位置没有问题。但首先我必须使用谷歌地图。

是什么原因造成的?为什么我的应用程序可以在打开谷歌地图后获得位置?我的清单文件中需要其他权限吗?

我的代码块如下,

private static final int LOCATION_SERVICES_RESOLUTION_REQUEST = 9001;
private void initMainActivity() {
int fineAccessGranted = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
int coarseAccessGranted = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION);
int externalWrite = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
int externalRead = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
int camera = ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA);
ArrayList<String> permissionsNeeded = new ArrayList<String>();
if (fineAccessGranted == PackageManager.PERMISSION_DENIED)
permissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
if (coarseAccessGranted == PackageManager.PERMISSION_DENIED)
permissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
if (externalWrite == PackageManager.PERMISSION_DENIED)
permissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (externalRead == PackageManager.PERMISSION_DENIED)
permissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
if (camera == PackageManager.PERMISSION_DENIED)
permissionsNeeded.add(Manifest.permission.CAMERA);
if (permissionsNeeded.size() == 0) {
this.initMainActivityAfterPermissions();
} else {
ActivityCompat.requestPermissions(this, permissionsNeeded.toArray(new String[0]), LOCATION_SERVICES_RESOLUTION_REQUEST);
}
}

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case LOCATION_SERVICES_RESOLUTION_REQUEST: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
this.initMainActivityAfterPermissions();
} else {
}
return;
}

获取位置的代码片段;

result =  LocationServices.FusedLocationApi.getLastLocation(instance.mGoogleApiClient);

基本上,这意味着您试图通过mFusedLocationClient.getLastLocation()检索位置,但此时设备上没有位置。因此,您需要请求位置更新,如mFusedLocationClient.requestLocationUpdates。此链接将非常有用https://developer.android.com/training/location/receive-location-updates?hl=es和https://github.com/googlesamples/android-play-location

相关内容

最新更新