-
Notifications
You must be signed in to change notification settings - Fork 35
/
PermissionExt.kt
80 lines (66 loc) · 2.6 KB
/
PermissionExt.kt
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package luyao.util.ktx.ext.permission
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
/**
* Created by luyao
* on 2019/6/18 15:47
*/
const val TAG ="ktx"
/**
* request permissions list in [permissions]
*/
fun FragmentActivity.request(vararg permissions: String) {
ActivityCompat.requestPermissions(this, permissions, 0XFF)
}
/**
* request permissions list in [permissions]
* @param callbacks DSL callback to handle request result
*/
fun FragmentActivity.request(vararg permissions: String, callbacks: PermissionsCallbackDSL.() -> Unit) {
val permissionsCallback = PermissionsCallbackDSL().apply { callbacks() }
val requestCode = PermissionsMap.put(permissionsCallback)
val needRequestPermissions = permissions.filter { !isGranted(it) }
if (needRequestPermissions.isEmpty()) {
permissionsCallback.onGranted()
} else {
val shouldShowRationalePermissions = mutableListOf<String>()
val shouldNotShowRationalePermissions = mutableListOf<String>()
for (permission in needRequestPermissions) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission))
shouldShowRationalePermissions.add(permission)
else
shouldNotShowRationalePermissions.add(permission)
}
if (shouldShowRationalePermissions.isNotEmpty()) {
permissionsCallback.onShowRationale(
PermissionRequest(
getKtxPermissionFragment(this),
shouldShowRationalePermissions,
requestCode
)
)
}
if (shouldNotShowRationalePermissions.isNotEmpty()) {
getKtxPermissionFragment(this).requestPermissionsByFragment(
shouldNotShowRationalePermissions.toTypedArray(),
requestCode
)
}
}
}
private fun getKtxPermissionFragment(activity: FragmentActivity): KtxPermissionFragment {
var fragment = activity.supportFragmentManager.findFragmentByTag(TAG)
if (fragment == null) {
fragment = KtxPermissionFragment()
activity.supportFragmentManager.beginTransaction().add(fragment, TAG).commitNow()
}
return fragment as KtxPermissionFragment
}
fun Activity.isGranted(permission: String): Boolean {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
}