我试图制作一个使用位置的应用程序。当我想要位置更新时,出现错误并显示“呼叫需要权限,而该权限可能会被用户拒绝:代码应显式检查以查看权限是否可用(带有checkPermission)或显式处理潜在的SecurityException”
这就是我试图在代码中添加的内容
if (ContextCompat.checkSelfPermission( this,android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED )
{
ActivityCompat.requestPermissions(
this,
new String [] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
LocationService.MY_PERMISSION_ACCESS_COARSE_LOCATION
);
}
但是在我输入之后,我在LocationService上收到一个错误,提示“无法解析符号LocationService”。
这是我的代码
public void onCreate() {
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
contentIntent = PendingIntent.getActivity(
this, 0, notificationIntent, 0);
//updateNotification(false);
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
mLocationManager.addGpsStatusListener(this);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, this);
}
答案 0 :(得分:0)
在运行时请求使用设备当前位置的权限,如下所示:
if (ActivityCompat.checkSelfPermission(YourActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(YourActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(YourActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}else{
// Write you code here if permission already given.
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
mLocationManager.addGpsStatusListener(this);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, this);
}
用户是否允许使用设备当前位置时的句柄:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Write you code here if permission already given.
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
mLocationManager.addGpsStatusListener(this);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, this);
} }else{
// you must ask location permission again
}
}
答案 1 :(得分:0)
在清单文件集中
android.permission.ACCESS_COARSE_LOCATION
对网络提供商的许可,或
android.permission.ACCESS_FINE_LOCATION
对于GPS提供程序。