Skip to content

Commit 5e9c471

Browse files
committed
Add OS permissions request helper
1 parent 2ae8df0 commit 5e9c471

File tree

1 file changed

+52
-0
lines changed
  • templates/android/library/src/main/java/io/package

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
}

0 commit comments

Comments
 (0)