I am trying to store my token in my cloud DB. I am going to use this token later in a cloud function in order to send a notification to a user that has been added as a friend.
Pushing the device token however does not work because the user is unauthorized. I can't save it after they are authorized because the token is generated when the app is installed.
private static final String TAG = "FirebaseIDService";
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
}
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* @param token The new token.
*/
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference deviceToken = mFirebaseDatabase.getReference("device_token");
deviceToken.push().setValue(token).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Log.i("token push","Success!");
} else {
Log.i("token push","Failed !");
}
});
}
Save the token in SharedPreferences, after a successful login save the token to Firebase database, keep in mind that if you remove the app cache or reinstall the app the token is always different