gpt4 book ai didi

java - 位置需要许可

转载 作者:行者123 更新时间:2023-12-02 03:29:42 25 4
gpt4 key购买 nike

我尝试制作一个使用位置的应用程序。当我想要位置更新时,会出现错误并显示“调用需要权限,可能会被用户拒绝:代码应显式检查权限是否可用(使用 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);

}

最佳答案

在运行时请求许可以使用设备当前位置,如下所示:

    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
}
}

关于java - 位置需要许可,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56892759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com