create-request-permission-listener.uvue 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <template>
  2. <!-- #ifdef APP -->
  3. <scroll-view style="flex:1">
  4. <!-- #endif -->
  5. <page-head title="权限申请监听"></page-head>
  6. <view class="permission-alert" id="permission-alert"
  7. :style="{'transform':isPermissionAlertShow ? 'translateY(0)':'translateY(-110px)'}">
  8. <text style="font-size: 20px;margin-bottom: 10px;margin-top: 5px;">访问日历权限申请说明:</text>
  9. <text style="color: darkgray;">uni-app x正在申请访问日历权限用于演示,允许或拒绝均不会获取任何隐私信息。</text>
  10. </view>
  11. <button type="primary" style="margin: 10px;" @click="requestPermission">点击申请日历权限</button>
  12. <!-- #ifdef APP -->
  13. </scroll-view>
  14. <!-- #endif -->
  15. </template>
  16. <script>
  17. export default {
  18. data() {
  19. return {
  20. isPermissionAlertShow: false,
  21. permissionAlert: null as UniElement | null,
  22. timeoutId: -1,
  23. permissionListener: null as RequestPermissionListener | null
  24. }
  25. },
  26. onReady() {
  27. this.watchPermissionRRequest()
  28. },
  29. onUnload() {
  30. this.permissionListener?.stop()
  31. this.permissionListener = null
  32. clearTimeout(this.timeoutId)
  33. },
  34. methods: {
  35. watchPermissionRRequest() {
  36. this.permissionListener = uni.createRequestPermissionListener()
  37. this.permissionListener!.onConfirm((_) => {
  38. // TODO 目前onConfirm监听实现的在时间上不够精确,暂时需要延迟弹框,后续修复
  39. // TODO 这里的弹框仅为演示,实际开发中监听权限申请的代码应该在app.uvue中,弹框应全局处理,可参考https://gitcode.net/dcloud/uni-api/-/tree/master/uni_modules/uni-prompt/utssdk/app-android 代码自行封装一个uts的全局弹框
  40. this.timeoutId = setTimeout(() => {
  41. this.isPermissionAlertShow = true
  42. }, 100)
  43. })
  44. this.permissionListener!.onComplete((_) => {
  45. clearTimeout(this.timeoutId)
  46. this.isPermissionAlertShow = false
  47. })
  48. },
  49. requestPermission() {
  50. // #ifdef APP-ANDROID
  51. if (UTSAndroid.checkSystemPermissionGranted(UTSAndroid.getUniActivity()!, ["android.permission.READ_CALENDAR"])) {
  52. uni.showToast({
  53. title: "权限已经同意了,不需要再申请",
  54. position: "bottom"
  55. })
  56. return
  57. }
  58. UTSAndroid.requestSystemPermission(UTSAndroid.getUniActivity()!, ["android.permission.READ_CALENDAR"], (_ : boolean, p : string[]) => {
  59. console.log(p)
  60. }, (_ : boolean, p : string[]) => {
  61. uni.showToast({
  62. title: "权限被拒绝了",
  63. position: "bottom"
  64. })
  65. console.log(p)
  66. })
  67. // #endif
  68. }
  69. }
  70. }
  71. </script>
  72. <style>
  73. .permission-alert {
  74. width: 90%;
  75. height: 100px;
  76. margin: 10px 5%;
  77. position: absolute;
  78. top: 0px;
  79. z-index: 3;
  80. border-radius: 5px;
  81. transition-property: transform;
  82. transition-duration: 200ms;
  83. background-color: white;
  84. padding: 10px;
  85. }
  86. </style>