【问题标题】:Check if user online separate class检查用户是否在线单独上课
【发布时间】:2018-11-29 18:28:27
【问题描述】:

我想重复使用以下代码:

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();

正确吗?

【问题讨论】:

  • 如果你想重复使用它。那么它应该在单独的类中。
  • 您也可以签出this
  • 嘿@Stackpile 通过单击答案旁边的 V 形按钮之类的刻度标记,将答案标记为正确,它应该变成绿色。这有助于问题的未来读者,我也很感激。干杯! :)

标签: java android firebase firebase-realtime-database


【解决方案1】:

如果您使用的是 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 类中,并使用你展示的代码,它看起来大部分都是正确的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多