使用 try and catch 请求 Android 运行 时间权限
Requesting Android run-time permissions using try and catch
我想知道使用 Java 的 try 和 catch 语句来请求用户应用程序权限是否有意义, 如果我们得到 SecurityException?
粗略的例子是:
int hasReadExternalStoragePermission = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (hasReadExternalStoragePermission != PackageManager.PERMISSION_GRANTED) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(
MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// inform user
}
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_READ_EXTERNAL_STORAGE_OPEN_PROJECT);
return;
}
myFunction();
对比
try {
myFunction();
} catch (SecurityException) {
ActivityCompat.requestPermissions(
MainActivity.this,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE);
return;
}
两种方法的优缺点?
关于未检查异常的一些想法:https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
回想一下SecurityException
是运行时异常,我强调一下这部分:
Runtime exceptions represent problems that are the result of a programming problem, (...)
所以我理解抛出后请求权限SecurityException
意味着程序在调用操作之前没有检查应用程序是否具有某些特定权限的问题。我特别避免开发有问题的程序。
尽管如此,两种代码的工作原理相同。
我一直在想 tiny window 在调用 checkSelfPermission
和 [=11= 之间删除权限的机会].这将是支持 try ... catch
选项的论据。但是,我所做的一些实验表明,虽然可以将权限添加到 运行 应用程序,但如果删除权限,则该应用程序将被终止。
我看到的所有小例子都显示在需要权限之前调用checkSelfPermission
,但在某些情况下,确保您尽早拥有权限可能会更好,并且您可以通过假设简化后续代码您继续拥有权限。
我想知道使用 Java 的 try 和 catch 语句来请求用户应用程序权限是否有意义, 如果我们得到 SecurityException?
粗略的例子是:
int hasReadExternalStoragePermission = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (hasReadExternalStoragePermission != PackageManager.PERMISSION_GRANTED) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(
MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// inform user
}
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_READ_EXTERNAL_STORAGE_OPEN_PROJECT);
return;
}
myFunction();
对比
try {
myFunction();
} catch (SecurityException) {
ActivityCompat.requestPermissions(
MainActivity.this,
new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE);
return;
}
两种方法的优缺点?
关于未检查异常的一些想法:https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
回想一下SecurityException
是运行时异常,我强调一下这部分:
Runtime exceptions represent problems that are the result of a programming problem, (...)
所以我理解抛出后请求权限SecurityException
意味着程序在调用操作之前没有检查应用程序是否具有某些特定权限的问题。我特别避免开发有问题的程序。
尽管如此,两种代码的工作原理相同。
我一直在想 tiny window 在调用 checkSelfPermission
和 [=11= 之间删除权限的机会].这将是支持 try ... catch
选项的论据。但是,我所做的一些实验表明,虽然可以将权限添加到 运行 应用程序,但如果删除权限,则该应用程序将被终止。
我看到的所有小例子都显示在需要权限之前调用checkSelfPermission
,但在某些情况下,确保您尽早拥有权限可能会更好,并且您可以通过假设简化后续代码您继续拥有权限。