@@ -5,6 +5,7 @@ import android.content.pm.PackageManager
5
5
import android.os.Bundle
6
6
import android.util.Log
7
7
import android.widget.Toast
8
+ import androidx.activity.result.contract.ActivityResultContracts
8
9
import androidx.annotation.RequiresApi
9
10
import androidx.appcompat.app.AppCompatActivity
10
11
import androidx.core.content.ContextCompat
@@ -96,8 +97,21 @@ class MainActivity : AppCompatActivity() {
96
97
// [END log_reg_token]
97
98
}
98
99
99
- @RequiresApi(33 )
100
100
// [START ask_post_notifications]
101
+ // Declare the launcher at the top of your Activity/Fragment:
102
+ private val requestPermissionLauncher = registerForActivityResult(
103
+ ActivityResultContracts .RequestPermission ()
104
+ ) { isGranted: Boolean ->
105
+ if (isGranted) {
106
+ // FCM SDK (and your app) can post notifications.
107
+ } else {
108
+ // TODO: Inform user that that your app will not show notifications.
109
+ }
110
+ }
111
+
112
+ // [START_EXCLUDE]
113
+ @RequiresApi(33 )
114
+ // [END_EXCLUDE]
101
115
private fun askNotificationPermission () {
102
116
if (ContextCompat .checkSelfPermission(this , Manifest .permission.POST_NOTIFICATIONS ) ==
103
117
PackageManager .PERMISSION_GRANTED
@@ -110,26 +124,9 @@ class MainActivity : AppCompatActivity() {
110
124
// If the user selects "No thanks," allow the user to continue without notifications.
111
125
} else {
112
126
// Directly ask for the permission
113
- requestPermissions(arrayOf( Manifest .permission.POST_NOTIFICATIONS ), NOTIFICATION_REQUEST_CODE )
127
+ requestPermissionLauncher.launch( Manifest .permission.POST_NOTIFICATIONS )
114
128
}
115
129
}
116
130
// [END ask_post_notifications]
117
131
118
- // [START handle_ask_post_notifications_request]
119
- override fun onRequestPermissionsResult (requestCode : Int , permissions : Array <out String >, grantResults : IntArray ) {
120
- super .onRequestPermissionsResult(requestCode, permissions, grantResults)
121
- when (requestCode) {
122
- NOTIFICATION_REQUEST_CODE -> {
123
- // If request is cancelled, the result arrays are empty.
124
- if (grantResults.isNotEmpty() && grantResults[0 ] == PackageManager .PERMISSION_GRANTED ) {
125
- // FCM SDK (and your app) can post notifications.
126
- } else {
127
- // TODO: Inform user that that your app will not show notifications.
128
- }
129
- return
130
- }
131
- }
132
- }
133
- // [END handle_ask_post_notifications_request]
134
-
135
132
}
0 commit comments