在应用程序中一次性登录 - FirebaseAuth [英] One time login in app - FirebaseAuth
问题描述
我正在开发一款使用 Firebase 身份验证通过电话号码登录用户的应用.我想添加一个功能,以便用户只有一次登录,即即使用户杀死应用程序并再次启动它,他也应该登录.另外,我不想添加注销功能.可以为此做些什么?
I'm working on an app that uses Firebase authentication to sign in users through phone number. I want to add a functionality such that there is only one-time login for the user, i.e. even if the user kills the app and starts it again, he should be logged in. Also, I don't want to add a logout feature. What can be done for this?
推荐答案
实现此目的的最简单方法是使用侦听器.假设您有两个活动,LoginActivity
和 MainActivity
.可以在 LoginActivity
中创建的侦听器应如下所示:
The simplest way to achieve this is to use a listener. Let's assume you have two activities, the LoginActivity
and the MainActivity
. The listener that can be created in the LoginActivity
should look like this:
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
};
这基本上意味着如果用户已登录,则跳过LoginActivity
并转到MainActivity
.
This basically means that if the user is logged in, skip the LoginActivity
and go to the MainActivity
.
实例化 FirebaseAuth
对象:
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
然后开始监听 onStart()
方法的变化,如下所示:
And start listening for changes in your onStart()
method like this:
@Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(authStateListener);
}
在MainActivity
中,你应该做同样的事情:
In the MainActivity
, you should do the same thing:
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser == null) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
}
};
这基本上意味着如果用户没有登录,跳过MainActivity
并转到LoginActivity
.在此活动中,您应该执行与 LoginActivity
中相同的操作,您应该开始侦听 onStart()
中的更改.
Which basically means that if the user is not logged in, skip the MainActivity
and go to the LoginActivity
. In this activity you should do the same thing as in the LoginActivity
, you should start listening for changes in the onStart()
.
在这两个活动中,不要忘记在不再需要的那一刻删除侦听器.因此,在您的 onStop()
方法中添加以下代码行:
In both activities, don't forget to remove the listener in the moment in which is not needed anymore. So add the following line of code in your onStop()
method:
@Override
protected void onStop() {
super.onStop();
firebaseAuth.removeAuthStateListener(authStateListener);
}
这篇关于在应用程序中一次性登录 - FirebaseAuth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!