How to work with FirebaseAuth inside Android Module

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 16:38:53

You need to add a listener/Observer to get the userid for every auth state change.

FirebaseAuth.getInstance().addAuthStateListener(firebaseAuth -> {
            if (firebaseAuth.getCurrentUser() == null) {
                your code goes here
            }
        });

https://firebase.google.com/docs/auth/android/manage-users

Another method wkile login get the user id and store in LocalStorage, while logout clear the localstorage, so that you will be able to maintain in offline too.

In Android, FirebaseApp object manages the configuration for all the Firebase APIs. This is initialized automatically by a content provider when your app is launched, and you typically never need to interact with it. However, when you want to access multiple projects from a single app, you'll need a distinct FirebaseApp to reference each one individually.

Before initializing your second project, make sure Firebase defaultApp instance is initialized. Call FirebaseDatabase.getInstance() from your base/main project's Application class - OnCreate() as below,

// Primary project database
FirebaseDatabase database = FirebaseDatabase.getInstance();

To connect second project database from your library project, initialize FirebaseApp with secondary configuration along with some distinct identifier(eg:"secondary") as below,

FirebaseOptions options = new FirebaseOptions.Builder()
       .setApplicationId("1:530266078999:android:481c4ecf3253701e") // Required for Analytics.
       .setApiKey("AIzaSyBRxOyIj5dJkKgAVPXRLYFkdZwh2Xxq51k") // Required for Auth.
       .setDatabaseUrl("https://project-1765055333176374514.firebaseio.com/") // Required for RTDB.
       .build();
FirebaseApp.initializeApp(this /* Context */, options, "secondary");

Then retrive the secound App

// Retrieve the second app.
FirebaseApp secondApp = FirebaseApp.getInstance("secondary");
// Get the database of second app.
FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(secondApp);

Note: Inside your library module, make sure you always refer your second project. Better create a singleton reference

// Make singleton reference
public static FirebaseApp getFirebaseApp() {
    if (mFirebaseApp == null) {
        Context context = getAppContext();
        FirebaseOptions options = getLibraryModuleFirebaseOptions();
        mFirebaseApp = FirebaseApp.initializeApp(context, options, "library");
    }
    return mFirebaseApp;
} 

For detailed information, please refer the Firebase blog post here

Hope this would help you..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!