【问题标题】:Access user information across activities Firebase Android跨活动访问用户信息 Firebase Android
【发布时间】:2016-06-20 21:49:57
【问题描述】:

在一个活动中,我正在为用户登录,然后它转到另一个向用户致意的活动。我正在使用内置的 Firebase 方法使用电子邮件/密码登录用户。我在 Firebase 数据库中有 UID,它与一个名称相关联。我只是在 Firebase 中手动输入用户,稍后将实施注册活动。如何在第二个活动中访问用户的 UID?

【问题讨论】:

    标签: android firebase firebase-realtime-database firebase-authentication


    【解决方案1】:

    除了传递 uid 之外,您还可以 use an auth state listener to detect the user in each activity。从该文档页面:

    mAuthListener = 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");
            }
            // ...
        }
    };
    

    此代码通常会进入您从中派生活动的基类。

    【讨论】:

    • 我还需要在登录类中添加它吗?我在问候语课上试过这个,但它不起作用。这会从 Firebase 创建的存储的 Auth Token 中获取数据吗?
    • 认证状态确实在activity之间持久化了。
    • 嗨@FrankvanPuffelen 你知道会话在哪里持续存在吗?可能是共享偏好?谢谢
    • 没关系,它存储在共享首选项中,刚刚检查过,还是谢谢
    【解决方案2】:

    随便用

    FirebaseAuth mAuth;
    
    mAuth = FirebaseAuth.getInstance();
    
    FirebaseUser user = mAuth.getCurrentUser();
    
    String UID = user.getUid();
    

    它会自动从以前的活动中获取用户。

    【讨论】:

    • 您确定您的代码不会重新请求服务器以取回相同的实例吗?
    【解决方案3】:

    您应该将其保存在SharedPreferences 中并在第二个活动中检索它,或者通过Intent 对象将其传递到第二个活动中。

    SharedPreferences 是在应用程序中持久存储数据的一种更简单的方法。存储在SharedPreferences 中的数据几乎可以从应用程序的任何位置检索和修改。数据将在手机重启甚至应用程序卸载后仍然存在,因为它可以由系统备份。 Here是官方解释。而here 是一个很好的教程。

    【讨论】:

    • 你能扩展一下 SharedPreferences 部分吗?
    猜你喜欢
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多