java - 检查用户是否在线单独上课
问题描述
我想重用以下代码:
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();
这是对的吗?
解决方案
如果您使用的是 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 类中,并使用您展示的代码,它看起来大多是正确的。
推荐阅读
- bash - bash如何有选择地删除字符串中的空格
- postman - 邮递员是否支持保存收集运行器?
- c# - 使用 CSVhelper 将单个列更新为先前编写的 CSV 文件。我有 Java 代码,但无法将其翻译成 C#
- composer-php - 精确版本的 TYPO3 的作曲家设置
- firebase - 如何编写firestore规则来查询另一个集合,其中值等于某个值
- javascript - 使用一行中的数据在 ag-grid (Vue.js) 中创建自定义聚合函数
- openapi - OpenAPI 中正则表达式“模式”的共同点是什么?
- java - Spring Boot 属性解析不正确
- c++ - Check for end-of-list in boost::intrusive::list without container?
- javascript - 如何抓取网页内容需要点击按钮