Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion messaging/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ dependencies {
implementation("com.google.android.material:material:1.14.0")

// Import the Firebase BoM (see: https://firebase.google.com/docs/android/learn-more#bom)
implementation(platform("com.google.firebase:firebase-bom:34.14.1"))
implementation(platform("com.google.firebase:firebase-bom:34.15.0"))

// Firebase Cloud Messaging
implementation("com.google.firebase:firebase-messaging")
Expand Down
5 changes: 5 additions & 0 deletions messaging/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
<!-- [END fcm_default_channel] -->
<!-- [START Enable FCM New FCM Registration using Installation id] -->

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enable FCM New FCM Registration using Installation id

nit: should this be a variable name with '_' delimiter such as fcm_installation_id_enabled?

<meta-data
android:name="firebase_messaging_installation_id_enabled"
android:value="true" />
<!-- [END Enable FCM New FCM Registration using Installation id] -->
<activity
android:name=".EntryChoiceActivity"
android:label="@string/app_name"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,30 +106,21 @@ public void onComplete(@NonNull Task<Void> task) {
}
});

binding.logTokenButton.setOnClickListener(new View.OnClickListener() {
binding.logRegistrationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get token
// [START log_reg_token]
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "Fetching FCM registration token failed", task.getException());
return;
}
// Get FCM Registration
// [START log_reg]
FirebaseMessaging.getInstance().register()
.addOnCompleteListener(task -> {
if (!task.isSuccessful()) {
Log.w(TAG, "Fetching FCM registration failed", task.getException());
}

// Get new FCM registration token
String token = task.getResult();

// Log and toast
String msg = getString(R.string.msg_token_fmt, token);
Log.d(TAG, msg);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
// If the registration task is success, the onRegistered callback in
// FirebaseMessagingService will be invoked and the registration will be logged from there.
});
// [END log_reg_token]
// [END log_reg]
}
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,12 @@
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.google.firebase.quickstart.fcm.R;
Expand Down Expand Up @@ -106,26 +109,71 @@ public void onMessageReceived(RemoteMessage remoteMessage) {
// [END receive_message]


// [START on_new_token]
/**
* There are two scenarios when onNewToken is called:
* 1) When a new token is generated on initial app startup
* 2) Whenever an existing token is changed
* Under #2, there are three scenarios when the existing token is changed:
* A) App is restored to a new device
* B) User uninstalls/reinstalls the app
* C) User clears app data
*/
@Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);

// 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);
}
// [END on_new_token]
// [START onRegistered]
/**
* Called when the current app instance has been successfully registered with FCM.
*
* <p>This method provides the unique Firebase Installation ID (FID), which should be used to
* target this app instance for direct-send messaging.
*
* <p>This callback is triggered in the following scenarios:
*
* <ul>
* <li>When the registration first succeeds after app install (if auto-init is enabled).
* <li>When the registration is refreshed due to invalidation or updates (if auto-init is
* enabled).
* <li>Immediately after a direct call to {@link FirebaseMessaging#register()}.
* </ul>
*
* <p>Ensure the provided `installationId` is uploaded if it hasn't been previously or it might
* have been deleted on 404s.
*
* <p><b>Note:</b> To use this API, you must enable it by adding {@code <meta-data
* android:name="firebase_messaging_installation_id_enabled" android:value="true" />} to your
* app's manifest.
*
* @param installationId The Firebase Installation ID used for sending messages to the current app
* instance.
*/
@Override
public void onRegistered(@NonNull String installationId) {
Log.d(TAG, "Registration: " + installationId);

// If you want to send messages to this application instance or
// manage these apps subscriptions on the server side, send the
// FCM registration to your app server.
sendRegistrationToServer(installationId);

// Log and toast
String msg = getString(R.string.msg_registration_fmt, installationId);
Log.d(TAG, msg);
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
Comment thread
eldhosembabu marked this conversation as resolved.
Outdated
}
// [END onRegistered]

// [START onRegistered]
/**
* Called when the current app instance has been successfully unregistered from FCM via a call to
* {@code FirebaseMessaging.unregister()}.
*
* <p>This method confirms that the specified FID is no longer active for receiving FCM messages.
*
* <p><b>Note:</b> To use this API, you must enable it by adding {@code <meta-data
* android:name="firebase_messaging_installation_id_enabled" android:value="true" />} to your
* app's manifest.
*
* @param installationId The Firebase Installation ID of the current app instance that was
* unregistered with FCM.
*/
@Override
public void onUnregistered(@NonNull String installationId) {
super.onUnregistered(installationId);
// Remove FCM registration associated with the app instance on the app server
// so that the app server will not try to send FCM messages to the un registered app instance.
removeRegistrationFromServer(installationId);
}

// [START onRegistered]
Comment thread
eldhosembabu marked this conversation as resolved.
Outdated

/**
* Schedule async work using WorkManager.
Expand All @@ -146,17 +194,29 @@ private void handleNow() {
}

/**
* Persist token to third-party servers.
* Persist registration to third-party servers.
*
* Modify this method to associate the user's FCM registration token with any
* Modify this method to associate the user's FCM registration with any
* server-side account maintained by your application.
*
* @param token The new token.
* @param registration The new FCM registration.
*/
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
private void sendRegistrationToServer(String registration) {
// TODO: Implement this method to send FCM registration to your app server.
}

/**
* Remove registration from third-party servers.
*
* Modify this method to disassociate the user's FCM registration with any
* server-side account maintained by your application.
*
* @param registration The FCM registration which is unregistered.
*/
private void removeRegistrationFromServer(String registration) {
// TODO: Implement this method to remove FCM registration from your app server.
}

/**
* Create and show a simple notification containing the received FCM message.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,23 +85,18 @@ class MainActivity : AppCompatActivity() {
// [END subscribe_topics]
}

binding.logTokenButton.setOnClickListener {
// Get token
// [START log_reg_token]
Firebase.messaging.token.addOnCompleteListener(
binding.logRegistrationButton.setOnClickListener {
// Get FCM Registration
// [START log_reg]
Firebase.messaging.register().addOnCompleteListener(
OnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w(TAG, "Fetching FCM registration token failed", task.exception)
Log.w(TAG, "Fetching FCM registration failed", task.exception)
return@OnCompleteListener
}

// Get new FCM registration token
val token = task.result

// Log and toast
val msg = getString(R.string.msg_token_fmt, token)
Log.d(TAG, msg)
Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
// If the registration task is success, the onRegistered callback in
// FirebaseMessagingService will be invoked and the registration will be logged from there.
},
)
// [END log_reg_token]
Comment thread
eldhosembabu marked this conversation as resolved.
Outdated
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import android.content.Intent
import android.media.RingtoneManager
import android.os.Build
import android.util.Log
import android.widget.Toast
import androidx.core.app.NotificationCompat
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
Expand Down Expand Up @@ -65,23 +66,74 @@ class MyFirebaseMessagingService : FirebaseMessagingService() {

private fun isLongRunningJob() = true

// [START on_new_token]
/**
* Called if the FCM registration token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the
* FCM registration token is initially generated so this is where you would retrieve the token.
*/
override fun onNewToken(token: String) {
Log.d(TAG, "Refreshed token: $token")

// 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)
}
// [END on_new_token]

/**
// [START onRegistered]
/**
* Called when the current app instance has been successfully registered with FCM.
*
*
* This method provides the unique Firebase Installation ID (FID), which should be used to
* target this app instance for direct-send messaging.
*
*
* This callback is triggered in the following scenarios:
*
*
* * When the registration first succeeds after app install (if auto-init is enabled).
* * When the registration is refreshed due to invalidation or updates (if auto-init is
* enabled).
* * Immediately after a direct call to [FirebaseMessaging.register].
*
*
*
* Ensure the provided `installationId` is uploaded if it hasn't been previously or it might
* have been deleted on 404s.
*
*
* **Note:** To use this API, you must enable it by adding `<meta-data android:name="firebase_messaging_installation_id_enabled" android:value="true" />` to your
* app's manifest.
*
* @param installationId The Firebase Installation ID used for sending messages to the current app
* instance.
*/
public override fun onRegistered(installationId: String) {
Log.d(TAG, "Registration: " + installationId)

// If you want to send messages to this application instance or
// manage these apps subscriptions on the server side, send the
// FCM registration to your app server.
sendRegistrationToServer(installationId)

// Log and toast
val msg = getString(R.string.msg_registration_fmt, installationId)
Log.d(TAG, msg)
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
Comment thread
eldhosembabu marked this conversation as resolved.
Outdated
}

// [END onRegistered]

// [START onRegistered]
/**
* Called when the current app instance has been successfully unregistered from FCM via a call to
* `FirebaseMessaging.unregister()`.
*
*
* This method confirms that the specified FID is no longer active for receiving FCM messages.
*
*
* **Note:** To use this API, you must enable it by adding `<meta-data android:name="firebase_messaging_installation_id_enabled" android:value="true" />` to your
* app's manifest.
*
* @param installationId The Firebase Installation ID of the current app instance that was
* unregistered with FCM.
*/
public override fun onUnregistered(installationId: String) {
super.onUnregistered(installationId)
// Remove FCM registration associated with the app instance on the app server
// so that the app server will not try to send FCM messages to the un registered app instance.
removeRegistrationFromServer(installationId)
}
Comment thread
eldhosembabu marked this conversation as resolved.
Outdated

/**
* Schedule async work using WorkManager.
*/
private fun scheduleJob() {
Expand All @@ -98,18 +150,29 @@ class MyFirebaseMessagingService : FirebaseMessagingService() {
Log.d(TAG, "Short lived task is done.")
}

/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM registration token with any server-side account
* maintained by your application.
*
* @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)")
}
/**
* Persist registration to third-party servers.
*
* Modify this method to associate the user's FCM registration with any
* server-side account maintained by your application.
*
* @param registration The new FCM registration.
*/
private fun sendRegistrationToServer(registration: String?) {
// TODO: Implement this method to send FCM registration to your app server.
}

/**
* Remove registration from third-party servers.
*
* Modify this method to disassociate the user's FCM registration with any
* server-side account maintained by your application.
*
* @param registration The FCM registration which is unregistered.
*/
private fun removeRegistrationFromServer(registration: String?) {
// TODO: Implement this method to remove FCM registration from your app server.
}

/**
* Create and show a simple notification containing the received FCM message.
Expand Down
2 changes: 1 addition & 1 deletion messaging/app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
android:text="@string/subscribe_to_weather" />

<Button
android:id="@+id/logTokenButton"
android:id="@+id/logRegistrationButton"
Comment thread
eldhosembabu marked this conversation as resolved.
android:layout_width="@dimen/standard_field_width"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
Expand Down
2 changes: 1 addition & 1 deletion messaging/app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<string name="log_token">Log Token</string>

<string name="msg_subscribed">Subscribed to weather topic</string>
<string name="msg_token_fmt" translatable="false">FCM registration Token: %s</string>
<string name="msg_registration_fmt" translatable="false">FCM registration : %s</string>

<string name="default_notification_channel_id" translatable="false">fcm_default_channel</string>
<!--
Expand Down
Loading