Firebase: How to keep an Android user logged in?

前端 未结 4 1671
猫巷女王i
猫巷女王i 2021-02-05 11:53

I\'m using Firebase SimpleLogin to enable Email / Password authentication. Creation of users and subsequent login is all working fine. However, whenever I leave the app (even if

相关标签:
4条回答
  • 2021-02-05 12:38

    You can do this by Using this Approach to escape logi page if User already logged in.

    private FirebaseAuth auth;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        auth = FirebaseAuth.getInstance();
    
        if (auth.getCurrentUser() != null) {
            startActivity(new Intent(Login_Activity.this, Home.class));
            finish();
        }
        setContentView(R.layout.activity_login_);
    
    0 讨论(0)
  • 2021-02-05 12:41

    [Engineer at Firebase] In order to transparently handle persistent sessions in the Firebase Simple Login Java client, you need to use the two-argument constructor which accepts an Android context, i.e. SimpleLogin(com.firebase.client.Firebase ref, android.content.Context context) every time you instantiate the Simple Login Java client.

    See https://www.firebase.com/docs/java-simple-login-api/javadoc/com/firebase/simplelogin/SimpleLogin.html for the full API reference.

    0 讨论(0)
  • 2021-02-05 12:42

    The proper way to do it is to use oAuth authentication:

    1. The user logs in.
    2. You generate an access token(oAuth2).
    3. Android app saves the token locally.
    4. Each time the comes back to the auth, he can use the token to to log in, unless the token has been revoked by you, or he changed his
    password.
    

    Luckily, firebase has an out of the box support for that, docs:

    https://www.firebase.com/docs/security/custom-login.html https://www.firebase.com/docs/security/authentication.html

    0 讨论(0)
  • 2021-02-05 12:50

    Another way - try this code in your onCreate:

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user != null) {
        // User is signed in
        Intent i = new Intent(LoginActivity.this, MainActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(i);
    } else {
        // User is signed out
        Log.d(TAG, "onAuthStateChanged:signed_out");
    }
    

    This will keep the user logged in by taking the user to the Main activity directly without stopping at registration activity. so the user will be logged in unless the user click on signout.

    0 讨论(0)
提交回复
热议问题