使用谷歌官方库 Accompanist 来请求权限,文档 https://google.github.io/accompanist/permissions/ 。
示例代码请求定位权限,因为要正常使用定位功能,不仅需要用户授予权限,还要用户打开【位置信息】(如下图),通过代码来判断是否已开启,如果没有开启,则提示用户去设置:

在 AndroidManifest.xml 声明所需的权限:
1 | <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> |
1 |
|
Limitations
This permissions wrapper is built on top of the available Android platform APIs. We cannot extend the platform’s capabilities. For example, it’s not possible to differentiate between the it’s the first time requesting the permission vs the user doesn’t want to be asked again use cases.
如文档所说,这个方案不是完美解决方案,在用户选择了“拒绝且不在提醒” 时,需要做特别处理。我使用 permissionRequested 做了一个简单的判断,但是在关闭应用后再次打开,需要点击两次才能出发正常的逻辑。
参考文档: