gpt4 book ai didi

java - 如何*正确*请求权限?

转载 作者:太空狗 更新时间:2023-10-29 16:10:31 25 4
gpt4 key购买 nike

我正在开发一个启动时需要 3 个权限的 Android 应用程序。我必须等到用户在对话框中做出响应,否则应用程序会崩溃,因为权限是强制性的。

请求这些权限的正确方法是什么?我编写了以下代码,但应用程序在响应第一个权限(拒绝或接受)时卡住。

这是我做的:

    String[] perms = {"Manifest.permission.READ_PHONE_STATE", "Manifest.permission.ACCESS_COARSE_LOCATION","Manifest.permission.CALL_PHONE"};

int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_PHONE_STATE);
int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
int result3 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CALL_PHONE);

if ((result1 == PackageManager.PERMISSION_GRANTED) && (result2 == PackageManager.PERMISSION_GRANTED) && (result3 == PackageManager.PERMISSION_GRANTED)) {
onPermissionGranted();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(perms, PERMISSION_REQUEST_CODE);
} else {
ActivityCompat.requestPermissions(this, perms, PERMISSION_REQUEST_CODE);
}

}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
onPermissionGranted();
// permission was granted, yay! Do the
// contacts-related task you need to do.

} else {
Toast.makeText(MainActivity.this, R.string.permission_required, Toast.LENGTH_LONG).show();
// permission denied, boo! Disable the
// functionality that depends on this permission.


}
return;
}

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

最佳答案

无需阻塞,无论是使用 Thread#sleep 还是使用 while 循环,因为权限请求是异步的。以下是您的 Activity 的流程:

首先,定义需要权限才能运行的逻辑:

private void onPermissionGranted() {
//code to execute
}

然后,在 onCreate() 中,检查您是否拥有这些权限。如果这样做,请执行您的代码。如果不这样做,请请求许可:

if (ContextCompat.checkSelfPermission(this,/*permissions*/) == PackageManager.PERMISSION_GRANTED) {
onPermissionGranted();
} else {
ActivityCompat.requestPermissions(this, /*permissions*/, /*request_code*/);
}

当权限状态更新后,它会调用 onRequestPermissionsResult。如果获得许可,则在此处执行操作。否则,执行其他操作(重新显示对话框或完成 Activity )。

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case /*our request code from before*/: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
onPermissionGranted();
} else {
Toast.makeText(this, "Permissions are required in order to run this app!", Toast.LENGTH_SHORT).show();
finish();
}
return;
}
}
}

关于java - 如何*正确*请求权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56292140/

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