1
1
package com.google.firebase.example.messaging.kotlin
2
2
3
+ import android.Manifest
4
+ import android.content.pm.PackageManager
3
5
import android.os.Bundle
4
6
import android.util.Log
5
7
import android.widget.Toast
8
+ import androidx.annotation.RequiresApi
6
9
import androidx.appcompat.app.AppCompatActivity
10
+ import androidx.core.content.ContextCompat
11
+ import com.google.firebase.example.messaging.MainActivity
7
12
import com.google.firebase.ktx.Firebase
8
13
import com.google.firebase.messaging.ktx.messaging
9
14
import com.google.firebase.messaging.ktx.remoteMessage
@@ -13,6 +18,7 @@ class MainActivity : AppCompatActivity() {
13
18
14
19
companion object {
15
20
private const val TAG = " MainActivity"
21
+ private const val NOTIFICATION_REQUEST_CODE = 1234
16
22
}
17
23
18
24
override fun onCreate (savedInstanceState : Bundle ? ) {
@@ -90,4 +96,40 @@ class MainActivity : AppCompatActivity() {
90
96
// [END log_reg_token]
91
97
}
92
98
99
+ @RequiresApi(33 )
100
+ // [START ask_post_notifications]
101
+ private fun askNotificationPermission () {
102
+ if (ContextCompat .checkSelfPermission(this , Manifest .permission.POST_NOTIFICATIONS ) ==
103
+ PackageManager .PERMISSION_GRANTED
104
+ ) {
105
+ // FCM SDK (and your app) can post notifications.
106
+ } else if (shouldShowRequestPermissionRationale(Manifest .permission.POST_NOTIFICATIONS )) {
107
+ // TODO: display an educational UI explaining to the user the features that will be enabled
108
+ // by them granting the POST_NOTIFICATION permission. This UI should provide the user
109
+ // "OK" and "No thanks" buttons. If the user selects "OK" directly request the permission.
110
+ // If the user selects "No thanks" allow the user to continue without notifications.
111
+ } else {
112
+ // Directly ask for the permission
113
+ requestPermissions(arrayOf(Manifest .permission.POST_NOTIFICATIONS ), NOTIFICATION_REQUEST_CODE )
114
+ }
115
+ }
116
+ // [END ask_post_notifications]
117
+
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
+
93
135
}
0 commit comments