@@ -5,6 +5,7 @@ import android.content.pm.PackageManager
55import android.os.Bundle
66import android.util.Log
77import android.widget.Toast
8+ import androidx.activity.result.contract.ActivityResultContracts
89import androidx.annotation.RequiresApi
910import androidx.appcompat.app.AppCompatActivity
1011import androidx.core.content.ContextCompat
@@ -96,8 +97,21 @@ class MainActivity : AppCompatActivity() {
9697 // [END log_reg_token]
9798 }
9899
99- @RequiresApi(33 )
100100 // [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]
101115 private fun askNotificationPermission () {
102116 if (ContextCompat .checkSelfPermission(this , Manifest .permission.POST_NOTIFICATIONS ) ==
103117 PackageManager .PERMISSION_GRANTED
@@ -110,26 +124,9 @@ class MainActivity : AppCompatActivity() {
110124 // If the user selects "No thanks," allow the user to continue without notifications.
111125 } else {
112126 // Directly ask for the permission
113- requestPermissions(arrayOf( Manifest .permission.POST_NOTIFICATIONS ), NOTIFICATION_REQUEST_CODE )
127+ requestPermissionLauncher.launch( Manifest .permission.POST_NOTIFICATIONS )
114128 }
115129 }
116130 // [END ask_post_notifications]
117131
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-
135132}
0 commit comments