-
Notifications
You must be signed in to change notification settings - Fork 399
/
MainActivity.kt
154 lines (139 loc) · 5.53 KB
/
MainActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package com.google.firebase.example.messaging.kotlin
import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.firestore
import com.google.firebase.Firebase
import com.google.firebase.messaging.messaging
import com.google.firebase.messaging.remoteMessage
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import java.util.concurrent.atomic.AtomicInteger
class MainActivity : AppCompatActivity() {
companion object {
private const val TAG = "MainActivity"
private const val NOTIFICATION_REQUEST_CODE = 1234
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// [START handle_data_extras]
intent.extras?.let {
for (key in it.keySet()) {
val value = intent.extras?.get(key)
Log.d(TAG, "Key: $key Value: $value")
}
}
// [END handle_data_extras]
}
fun runtimeEnableAutoInit() {
// [START fcm_runtime_enable_auto_init]
Firebase.messaging.isAutoInitEnabled = true
// [END fcm_runtime_enable_auto_init]
}
fun deviceGroupUpstream() {
// [START fcm_device_group_upstream]
val to = "a_unique_key" // the notification key
val msgId = AtomicInteger()
Firebase.messaging.send(
remoteMessage(to) {
setMessageId(msgId.get().toString())
addData("hello", "world")
},
)
// [END fcm_device_group_upstream]
}
fun sendUpstream() {
val SENDER_ID = "YOUR_SENDER_ID"
val messageId = 0 // Increment for each
// [START fcm_send_upstream]
val fm = Firebase.messaging
fm.send(
remoteMessage("[email protected]") {
setMessageId(messageId.toString())
addData("my_message", "Hello World")
addData("my_action", "SAY_HELLO")
},
)
// [END fcm_send_upstream]
}
fun subscribeTopics() {
// [START subscribe_topics]
Firebase.messaging.subscribeToTopic("weather")
.addOnCompleteListener { task ->
var msg = "Subscribed"
if (!task.isSuccessful) {
msg = "Subscribe failed"
}
Log.d(TAG, msg)
Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
}
// [END subscribe_topics]
}
fun logRegToken() {
// [START log_reg_token]
Firebase.messaging.getToken().addOnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w(TAG, "Fetching FCM registration token failed", task.exception)
return@addOnCompleteListener
}
// Get new FCM registration token
val token = task.result
// Log and toast
val msg = "FCM Registration token: $token"
Log.d(TAG, msg)
Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
}
// [END log_reg_token]
}
// [START ask_post_notifications]
// Declare the launcher at the top of your Activity/Fragment:
private val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission(),
) { isGranted: Boolean ->
if (isGranted) {
// FCM SDK (and your app) can post notifications.
} else {
// TODO: Inform user that that your app will not show notifications.
}
}
private fun askNotificationPermission() {
// This is only necessary for API level >= 33 (TIRAMISU)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED
) {
// FCM SDK (and your app) can post notifications.
} else if (shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)) {
// TODO: display an educational UI explaining to the user the features that will be enabled
// by them granting the POST_NOTIFICATION permission. This UI should provide the user
// "OK" and "No thanks" buttons. If the user selects "OK," directly request the permission.
// If the user selects "No thanks," allow the user to continue without notifications.
} else {
// Directly ask for the permission
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
}
// [END ask_post_notifications]
// [START get_store_token]
private suspend fun getAndStoreRegToken(): String {
val token = Firebase.messaging.token.await()
// Add token and timestamp to Firestore for this user
val deviceToken = hashMapOf(
"token" to token,
"timestamp" to FieldValue.serverTimestamp(),
)
// Get user ID from Firebase Auth or your own server
Firebase.firestore.collection("fcmTokens").document("myuserid")
.set(deviceToken).await()
return token
}
// [END get_store_token]
}