gpt4 book ai didi

安卓 M 权限 : checkSelfPermission() always returns -1

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:53 25 4
gpt4 key购买 nike

在我的应用程序中,我有一个需要多个权限的后台服务。因为 M OS 要求开发人员确保这些权限在运行时得到批准,所以我尝试使用以下代码检查权限。

getApplicationContext().checkSelfPermission()

我没有显示任何获得允许/拒绝的弹出窗口。相反,我在应用程序信息页面中允许了这些权限(在设置>应用程序>应用程序管理器>我的后台服务)但是尽管我在应用程序信息页面中启用了这些权限,上面的函数总是返回 -1。

如果我在应用程序信息页面上更改了权限批准,如何正确检查权限?

最佳答案

 public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {

// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.

//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);


} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {

// permission was granted, yay! Do the
// contacts-related task you need to do.
buildGoogleApiClient();
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)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mGoogleMap.setMyLocationEnabled(true);

} else {

// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}

// other 'case' lines to check for other
// permissions this app might request
}
}

你应该做这样的事情。

关于安卓 M 权限 : checkSelfPermission() always returns -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34652173/

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