Skip to content

Instantly share code, notes, and snippets.

@thenishchalraj
Created March 30, 2021 16:31
Show Gist options
  • Save thenishchalraj/978bff4b0ff73c316515b300557d707e to your computer and use it in GitHub Desktop.
Save thenishchalraj/978bff4b0ff73c316515b300557d707e to your computer and use it in GitHub Desktop.
[Java] MessagingServices extends FirebaseMessageService to get the FCM Device Token when the app is installed for the first time.
public class MessagingServices extends FirebaseMessagingService {
public MessagingServices() {
FirebaseInstallations.getInstance().getId().addOnCompleteListener(
task -> {
if (task.isSuccessful()) {
String token = task.getResult();
Log.i("token ---->>", token);
// store the token in shared preferences
PrefUtils.getInstance(getApplicationContext()).setValue(PrefKeys.FCM_TOKEN, token);
}
}
);
}
// either use below function to get the token or directly get from the shared preferences
public static String getToken(Context context) {
return PrefUtils.getInstance(context).getStringValue(PrefKeys.FCM_TOKEN, "");
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
try {
// whatever you want
} catch (Exception e) {
// whatever you want
e.printStackTrace();
}
}
@Override
public void onNewToken(@NotNull String token) {
super.onNewToken(token);
// whatever you want
}
}
@thenishchalraj
Copy link
Author

thenishchalraj commented Mar 30, 2021

Note:

The token doesn't change until you uninstall and install the app again, or refresh the token in case of any harm.

Click here for the Kotlin (dagger) version

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment