-
Notifications
You must be signed in to change notification settings - Fork 7.4k
sample implementation of registration tokens for FCM #1453
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
andreaowu
wants to merge
15
commits into
master
Choose a base branch
from
reg-token-sample
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
fca8b50
sample implementation of registration tokens for FCM
andreaowu 32c4b65
made changes according to comments
andreaowu 88f4bf5
Merge remote-tracking branch 'origin/master' into reg-token-sample
andreaowu 4ef6bba
resolve comments and remove logs
andreaowu 61a1767
fix scope
andreaowu 5692eb5
remove duped code and simplify
andreaowu 1ff3190
added code to remove expired tokens from topics
andreaowu cf9f113
fix functions code
andreaowu 7f876a4
small code cleanup
andreaowu baa8132
add snippets
andreaowu defd24c
have both optimized and non-optimized versions
andreaowu 248b3e6
use flag for whether to use optimized version or not
andreaowu d9cd34b
update code
andreaowu 8057452
fix: add tag
HYACCCINT 0b77e46
Merge pull request #1512 from firebase/cynthia-sample-tag
HYACCCINT File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,13 +7,19 @@ import android.content.Context | |
import android.content.Intent | ||
import android.media.RingtoneManager | ||
import android.os.Build | ||
import android.preference.PreferenceManager | ||
import android.util.Log | ||
import androidx.core.app.NotificationCompat | ||
import androidx.work.OneTimeWorkRequest | ||
import androidx.work.WorkManager | ||
import com.google.firebase.firestore.FieldValue | ||
import com.google.firebase.firestore.ktx.firestore | ||
import com.google.firebase.ktx.Firebase | ||
import com.google.firebase.messaging.FirebaseMessagingService | ||
import com.google.firebase.messaging.RemoteMessage | ||
import com.google.firebase.quickstart.fcm.R | ||
import java.util.* | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Avoid wildcard imports |
||
|
||
|
||
class MyFirebaseMessagingService : FirebaseMessagingService() { | ||
|
||
|
@@ -74,7 +80,7 @@ class MyFirebaseMessagingService : FirebaseMessagingService() { | |
// If you want to send messages to this application instance or | ||
// manage this apps subscriptions on the server side, send the | ||
// FCM registration token to your app server. | ||
sendRegistrationToServer(token) | ||
sendTokenToServer(token) | ||
} | ||
// [END on_new_token] | ||
|
||
|
@@ -95,6 +101,7 @@ class MyFirebaseMessagingService : FirebaseMessagingService() { | |
Log.d(TAG, "Short lived task is done.") | ||
} | ||
|
||
// [START send_token_to_server] | ||
/** | ||
* Persist token to third-party servers. | ||
* | ||
|
@@ -103,10 +110,20 @@ class MyFirebaseMessagingService : FirebaseMessagingService() { | |
* | ||
* @param token The new token. | ||
*/ | ||
private fun sendRegistrationToServer(token: String?) { | ||
// TODO: Implement this method to send token to your app server. | ||
Log.d(TAG, "sendRegistrationTokenToServer($token)") | ||
private fun sendTokenToServer(token: String?) { | ||
// If you're running your own server, call API to send token and today's date for the user | ||
|
||
// Example shown below with Firestore | ||
// 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) | ||
} | ||
// [END send_token_to_server] | ||
|
||
/** | ||
* Create and show a simple notification containing the received FCM message. | ||
|
35 changes: 35 additions & 0 deletions
35
messaging/app/src/main/java/com/google/firebase/quickstart/fcm/kotlin/UpdateTokenWorker.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package com.google.firebase.quickstart.fcm.kotlin | ||
|
||
import android.content.Context | ||
import androidx.work.CoroutineWorker | ||
import androidx.work.WorkerParameters | ||
import com.google.firebase.firestore.FieldValue | ||
import com.google.firebase.firestore.ktx.firestore | ||
import com.google.firebase.ktx.Firebase | ||
import com.google.firebase.messaging.ktx.messaging | ||
import kotlinx.coroutines.tasks.await | ||
|
||
class UpdateTokenWorker(appContext: Context, workerParams: WorkerParameters): | ||
CoroutineWorker(appContext, workerParams) { | ||
|
||
override suspend fun doWork(): Result { | ||
// Refresh the token and send it to your server | ||
var token = Firebase.messaging.token.await() | ||
|
||
// If you have your own server, call API to send the above token and Date() for this user's device | ||
|
||
// Example shown below with Firestore | ||
// 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() | ||
|
||
// Indicate whether the work finished successfully with the Result | ||
return Result.success() | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
'use strict'; | ||
|
||
const functions = require('firebase-functions'); | ||
const admin = require('firebase-admin'); | ||
|
||
admin.initializeApp(); | ||
|
||
const EXPIRATION_TIME = 1000 * 60 * 60 * 24 * 60; // 60 days | ||
|
||
/** | ||
* Scheduled function that runs once a day. It retrieves all stale tokens then | ||
* unsubscribes them from 'topic1' then deletes them. | ||
* | ||
* Note: weather is an example topic here. It is up to the developer to unsubscribe | ||
* all topics the token is subscribed to. | ||
*/ | ||
// [START remove_stale_tokens] | ||
exports.pruneTokens = functions.pubsub.schedule('every 24 hours').onRun(async (context) => { | ||
// Get all documents where the timestamp exceeds is not within the past month | ||
const staleTokensResult = await admin.firestore().collection('fcmTokens') | ||
.where("timestamp", "<", Date.now() - EXPIRATION_TIME) | ||
.get(); | ||
// Delete devices with stale tokens | ||
staleTokensResult.forEach(function(doc) { doc.ref.delete(); }); | ||
}); | ||
// [END remove_stale_tokens] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.