首页 > 解决方案 > 检查用户是否在线单独上课

问题描述

我想重用以下代码:

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

if (user != null) {
    // User is signed in
    // Redirect to signed-in flow
} else {
    // No user is signed in
    // Redirect to login activity
}

但作为 Java 和 Android 的初学者,我不确定以何种方式使用此代码。我应该在单独的类中使用它并以静态方式使用它吗?如果是这样,我在以下方面是否正确:

创建单独的类,称为IsUserLoggedIn.java

public class IsUserLoggedIn {    

    public static void isUserLogged() {
        if (user != null) {
        // User is signed in
        // Redirect to signed-in flow
        } else {
        // No user is signed in
        // Redirect to login activity
        }

    }        
}

在我想检查的任何活动中,我将以下内容放入onResume

IsUserLoggedIn isUserLoggedIn = new IsUserLoggedIn();
isUserLoggedIn.isUserLogged();

这是对的吗?

标签: javaandroidfirebasefirebase-realtime-database

解决方案


如果您使用的是 Firebase 数据库,那么您还可以将用户的当前状态保存在数据库中并仅从那里获得答案。

我的意思是,您可以loginStatus为数据库中的每个用户节点命名一个节点,您可以在用户登录或登录时将其设置为 true,在您的应用程序中设置为 false,当用户注销。

因此,上述想法的一些代码将如下所示:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(FirebaseAuth.getInstance().getUid());

// put this code where you grant user the access to log in

ref.child("loginStatus").setValue(true);

// now you can retrieve the value whenever you want in your app directly without using any new class

// to set the status to false, put this code in the code where you give user the option to log-out from your app

ref.child("loginStatus").setValue(false);

此外,如果您只想使用另一个类,您可以将代码放在一个新的 Java 类中,并使用您展示的代码,它看起来大多是正确的。


推荐阅读