File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
templates/android/library/src/main/java/io/package Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ package {{ sdk .namespace | caseDot }}
2
+
3
+ import android.Manifest
4
+ import android.content.pm.PackageManager
5
+ import android.os.Build
6
+ import androidx.activity.result.contract.ActivityResultContracts
7
+ import androidx.appcompat.app.AppCompatActivity
8
+ import androidx.core.content.ContextCompat
9
+
10
+ object OS {
11
+ fun requestPermission(
12
+ activity: AppCompatActivity,
13
+ permission: String,
14
+ onGranted: () -> Unit = {},
15
+ onDenied: () -> Unit = {},
16
+ onShowRationale: () -> Unit = {},
17
+ ) {
18
+ if (
19
+ Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
20
+ (permission == Manifest.permission.POST_NOTIFICATIONS && Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU)
21
+ ) {
22
+ onGranted()
23
+ return
24
+ }
25
+
26
+ if (ContextCompat.checkSelfPermission(
27
+ activity,
28
+ permission
29
+ ) == PackageManager.PERMISSION_GRANTED
30
+ ) {
31
+ onGranted()
32
+ } else if (activity.shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)) {
33
+ onShowRationale()
34
+ } else {
35
+ requestPermissionLauncher(activity, onGranted, onDenied).launch(permission)
36
+ }
37
+ }
38
+
39
+ private fun requestPermissionLauncher(
40
+ activity: AppCompatActivity,
41
+ onGranted: () -> Unit,
42
+ onDenied: () -> Unit,
43
+ ) = activity.registerForActivityResult(
44
+ ActivityResultContracts.RequestPermission(),
45
+ ) { isGranted: Boolean ->
46
+ if (isGranted) {
47
+ onGranted()
48
+ } else {
49
+ onDenied()
50
+ }
51
+ }
52
+ }
You can’t perform that action at this time.
0 commit comments