One time login in app - FirebaseAuth

2019-01-03 07:29发布

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?

3条回答
迷人小祖宗
2楼-- · 2019-01-03 07:39

This is from my working code from logging class:

   private void LoginUserAccount(String email, String password)
{
    if (TextUtils.isEmpty(email))
    {
        Toast.makeText(ResponseStartPage.this, "Please write Your Email", Toast.LENGTH_SHORT).show();
    }
    if (TextUtils.isEmpty(password))
    {
        Toast.makeText(ResponseStartPage.this, "Please write Your password", Toast.LENGTH_SHORT).show();
    }

    else
    {
        loadingBar.setTitle("Login Account");
        loadingBar.setMessage("Please wait for verification...");
        loadingBar.show();
        mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task)
            {
                if (task.isSuccessful())
                {
                    String online_user_id = mAuth.getCurrentUser().getUid();
                    String DeviceToken = FirebaseInstanceId.getInstance().getToken();

                    usersReference.child(online_user_id).child("device_token").setValue(DeviceToken)
                            .addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid)
                                {
                                    Intent mainIntent = new Intent(ResponseStartPage.this, ResponseMainActivity.class);
                                    mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(mainIntent);
                                    finish();
                                }
                            });


                }
                else
                {
                    Toast.makeText(ResponseStartPage.this, "Please Check your email and password", Toast.LENGTH_SHORT).show();
                }
                loadingBar.dismiss();
            }
        });
    }
}
查看更多
Emotional °昔
3楼-- · 2019-01-03 07:46

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

This basically means that if the user is logged in, skip the LoginActivity and go to the MainActivity.

Instantiate the FirebaseAuth object:

FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();

And start listening for changes in your onStart() method like this:

@Override
protected void onStart() {
    super.onStart();
    firebaseAuth.addAuthStateListener(authStateListener);
}

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

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

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);
}
查看更多
你好瞎i
4楼-- · 2019-01-03 07:50

You can save user login session in shared Preference

Do this when your login got Login Success

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", Activity.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.commit();

and When Your apps is Starts (like Splash or login Page) use this

 SharedPreferences sp=this.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
  boolean b = sp.getBoolean("key_name", false);
if(b==true){
//User Already Logged in skip login page and continue to next process
}else{
//User is Not logged in, show login Form
}

It will works for you.

查看更多
登录 后发表回答