Created
March 30, 2021 16:31
-
-
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.
This file contains 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
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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