美图欣赏 | 设为首页 | 加入收藏 | 网站地图

当前位置:电脑中国 > 编程 > 移动开发 >

关于Android动态权限处理更友好的方式(Kotlin)

2017-08-24 10:44|来源:未知 |作者:dnzg |点击:

关于Android动态权限处理更友好的方式(Kotlin),用户拒绝权限(如图片选择拒绝存储权限后显示空页)后,完全不知道该干什么。这是我们应该指导用户去开启权限(因为很多时候手比脑子更快的就点击了拒绝)。如下图:
这里写图片描述

首先定义一个权限处理的工具类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class PermissionUtils(private val context: Activity) {
 
    private var mHasPermissionRunnable: Runnable? = null
    private var mNoPermissionRunnable: Runnable? = null
    private var REQUEST_CODE_PERMISSION = 1000
 
    fun checkStoragePermission(hasPermissionDo: Runnable) {
        var permission = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
        checkPermission(permission, hasPermissionDo, Runnable {
            context.showPermissionDialog("不开启存储权限,无法访问相册哦~")
        })
    }
 
    fun checkCameraPermission(hasPermissionDo: Runnable) {
        var permission = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        checkPermission(permission, hasPermissionDo, Runnable {
            context.showPermissionDialog("不开启相机权限,无法拍照哦~")
        })
    }
 
    fun checkPermission(permissions: Array<out string="">, hasPermissionDo: Runnable, noPermissionDo: Runnable) {
        mHasPermissionRunnable = null
        mNoPermissionRunnable = null
        if (isPermissionsGranted(permissions)) hasPermissionDo.run()
        else if (ActivityCompat.shouldShowRequestPermissionRationale(context, permissions.get(0))) {
            noPermissionDo.run()
        } else {
            mHasPermissionRunnable = hasPermissionDo
            mNoPermissionRunnable = noPermissionDo
            ActivityCompat.requestPermissions(context, permissions, REQUEST_CODE_PERMISSION)
        }
    }
 
 
     fun isPermissionsGranted(permissions: Array<out string="">): Boolean {
        for (it in permissions) {
            if (ContextCompat.checkSelfPermission(context, it) != PackageManager.PERMISSION_GRANTED)
                return false
        }
        return true
    }
 
    private fun isAllGranted(grantResults: IntArray): Boolean {
        for (it in grantResults) {
            if (it != PackageManager.PERMISSION_GRANTED) return false
        }
        return true
    }
 
    fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out string="">, grantResults: IntArray) {
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (isAllGranted(grantResults))
                mHasPermissionRunnable?.run()
            else mNoPermissionRunnable?.run()
        }
    }
</out></out></out>
(责任编辑:dnzg)