如何在运行时检查权限而不抛出 SecurityException?
我设计了一个函数,可以从 SD 获取/设置资源,如果没有从 sd 找到资源,则从 Asset 中获取资源,如果可能,将资源写回 SD
此函数可以通过方法调用检查 SD 是否已安装且可访问...
boolean bSDisAvalaible = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
我设计的函数可以从一个应用程序(项目)到另一个应用程序(项目)使用(有或没有 android.permission.WRITE_EXTERNAL_STORAGE)
然后我想检查当前应用程序是否无需使用 SecurityException 即可拥有此特定权限。
是否存在一种“好的”方式来在运行时查询当前定义的权限?
I design a function that may get/set a resource from SD and if not found from sd then take it from Asset and if possible write the asset back to SD
This function may check by method invocation if SD is mounted and accessible...
boolean bSDisAvalaible = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
My designed function may be used from one app(project) to another (with or without android.permission.WRITE_EXTERNAL_STORAGE)
Then I would like to check if the current application has this particular permission without playing with SecurityException.
Does it exist a "nice" way to consult current defined permissions at runtime ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
您可以使用 Context.checkCallingorSelfPermission() 函数来实现此目的。这是一个例子:
You can use
Context.checkCallingorSelfPermission()
function for this. Here is an example:这也是另一种解决方案
This is another solution as well
您还可以使用这个:
You can also use this:
例如 Google 文档:
Like Google documentation:
分享我的方法,以防有人需要它们:
并调用它:
Sharing my methods in case someone needs them:
And to call it:
您应该通过以下方式检查权限(如Android 权限所述):
然后,将您的结果与以下任一者进行比较:
或:
You should check for permissions in the following way (as described here Android permissions):
then, compare your result to either:
or:
第 1 步 - 添加权限请求
第 2 步 - 处理权限结果
Step 1 - add permission request
Step 2 - Handle Permission result
对我来说效果很好的代码是:-
The code which works fine for me is :-
KOTLIN(运行时)的权限:(android.permission.WRITE_EXTERNAL_STORAGE)
检查清单中
Check Permissions In KOTLIN (RunTime)
In Manifest: (android.permission.WRITE_EXTERNAL_STORAGE)
启用 GPS 位置 Android Studio
MapsActivity.java
Enable GPS location Android Studio
MapsActivity.java