Check login on every activity

2020-05-27 01:40发布

问题:

I'm developing and app where the user must login before using it. I customized my titlebar and put a logout button there, to enable users to logout whenever they want, and login with another account. The app should then display the login activity again.

That works well, but my problem is with the back button. When the user logs out, the login activity show up, but if he presses back, the app returns to the previous page, enabling the user to use that activity again, even without login.

I have my onCreate() of every activity set up this way:

public void onCreate(Bundle savedInstanceState) {  
    // Activity code  
    checkLogin();  
}

And the checkLogin():

if (GlobalContext.getCurrentUser() == null) {
    Intent i = new Intent(this, LoginActivity.class);
    startActivityForResult(i, GlobalContext.REQUEST_LOGIN);
}

However that's not working like it should, my app crashes sometimes when I press back, sometimes it return to the previous activity like I said, and sometimes it does actually work.

How can I make the checkLogin() get called everytime the activity is (re)started?
Or there is another, better way to do what I want?

EDIT:

Based on @Gabriel's answer and the following diagram from the SDK references, I moved the checkLogin() to the onResume() method instead of the onCreate, solving my problem.

回答1:

Move the call to checkLogin() from onCreate() to onStart().



回答2:

What I suggest is to add you checkLogin() to acitivity onResume() as checking it in onCreate() method will cause to call check for login 1 time only when activity created.

Or even batter is to move it to

onAttachToWindow()

So every time your activity will come to front. onAttachToWindow() will be called and will check for login.



回答3:

In the fisrt Activity where the user logged in , try to Save a variable on your SharedPreferences like this :

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("logged", true); // set it to false when the user is logged out

      // Commit the edits!
      editor.commit();

And then in every Activity of yours , put this code to check if the user is logged in or not , if he is not logged in , so redirect him to the LoginActivity like this :

@Override
    protected void onStart(Bundle state){
       super.onStart(state);
       . . .

       // Restore preferences
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       boolean loggedIn = settings.getBoolean("logged", true);
       if(!loggedIn){
            Toast.makeText(this,"you are not logged in !!",3000).show();
            Intent i = new Intent(this,LoginActivity.class);
            startActivity(i);
       }
    }