Android 使用 firebase 登录和存储

Android login and storing with firebase

我是 android 编码的初学者。而且,我想为我的应用程序创建一个登录页面。我正在使用 Firebase 作为我的后端服务器。使用 Firebase 提供的身份验证服务能够成功创建用户。但是,正如我们所知,用户必须在安装应用程序时输入登录凭据。因此,任何人都建议我如何在 android 中开发此部分,它在应用程序安装时获取凭据并将其存储在本地,这样用户就无需在启动应用程序时一直输入凭据。 提前谢谢你们!

有多种方法可以在本地存储您的用户信息。但我认为在你的情况下使用 SharedPreference 将是最好的解决方案。

我假设你已经用 FireBase 初始化了所有相关的东西,那么首先我们需要检查我们的用户 是否在 之前登录过。要检查它,我们将使用 SharedPreferences.

@Override
public void onCreate() {
    super.onCreate();
    Firebase.setAndroidContext(this);
    // other setup code
    SharedPreferences mPrefs = getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE);
    if (mPrefs.getBoolean("is_logged_before",false)) {
        Intent i = new Intent(this, HomeActivity.class);
        startActivity(i);
    } else {
        // continue to login part
    }
}

然后你应该将你的用户信息保存到SharedPreferences,如果你registered/logged-in成功到FireBase。 FireBase 应该有 onSuccess 函数,用于监听您的登录请求的结果。所以只需将这里的用户信息和其他相关信息保存在本地到SharedPreferences.

@Override
public void onSuccess(Map<String, Object> result) {
    System.out.println("Successfully created user account with uid: " + result.get("uid"));
    mPrefs = mContext.getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = mPrefs.edit();
    editor.putString("userId", result.get("uid"));
    editor.putBoolean("is_logged_before",true); //this line will do trick
    editor.commit();
}

当用户登录时,Firebase 已经保留了会话(在 SharedPreferences 中)令牌,因此您不必自己这样做。

相反,您应该 monitor whether the user is logged in。来自该文档:

Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.addAuthStateListener(new Firebase.AuthStateListener() {
    @Override
    public void onAuthStateChanged(AuthData authData) {
        if (authData != null) {
            // user is logged in
        } else {
            // user is not logged in
        }
    }
});