3
votes

I'm working on a project where users should be able to use an app without any login. But they should also be able to login with their google account to sync their data with multiple devices.

How can I get a unique identifier for "anonymous" users? I know there exists a method such as .push().getKey() to get an uid from the realtime database, but where can I store this key on the device?

I'm also working with firebase authentication, so when people are using their google account for the app, I can use the Uid from firebase authentication. There is also an option for anonymous users in firebase authentication, but I dont want to go with that, because this would store the data only temporarily.

1
"but where can I store this key on the device?" - Firebase Database also has offline support. You can read more about it hereRosário Pereira Fernandes

1 Answers

1
votes

You're confusing two things:

  • Firebase Database has a method called push() that generates an ID that is statistically guaranteed to be unique.
  • Firebase Authentication generated a UID for each registered user that is guaranteed to be unique among all users.

The two values have no relation to each other.

If you want to identify a user, register the user with Firebase Authentication and use the UID of the user to identify them. If you don't want your users to have to sign in, use anonymous authentication. This as simple as:

FirebaseAuth.getInstance().signInAnonymously();

And then you get their UID by waiting for them to be registered:

FirebaseAuth.getInstance(). addAuthStateListener(new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            // User is signed in
            Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
        } else {
            // User is signed out
            Log.d(TAG, "onAuthStateChanged:signed_out");
        }
        // ...
    }
});;

The UID is automatically stored on the device for you. So onAuthStateChanged also fires when the user restarts the app. Be sure to only call signInAnonymously if the user hasn't been signed in before.