Android Best Practices for Verifying Entry into Each Activity

in my application, the user must authenticate before he can start using the application. I have this code in startupActivity

private boolean checkAuthentication() {
    SharedPreferences sp = getSharedPreferences(
            "com.simekadam.blindassistant", Context.MODE_PRIVATE);
    return sp.getBoolean("logged", false);
}

private void processStartup(){
    Log.d(TAG, "processing startup");
    if (checkAuthentication()) {
        Intent startApp = new Intent(getApplicationContext(),
                BlindAssistantActivity.class);
        startActivity(startApp);
    } else {

        Intent loginIntent = new Intent(getApplicationContext(), LoginActivity.class);
        startActivity(loginIntent);


    }
}

it just works, but I need to check it in every action (in the onStart or onResume methods), but this will lead to code duplication among all my actions. What is the best way to do this? Can I create a master activity that will be complemented by other actions?

thank

+3
source share
2 answers

Yes, you can create master activity and use "extends" for inheritance, but I would look at AppState if you were you.

, Application. "" .

: http://www.helloandroid.com/tutorials/maintaining-global-application-state

+7

, , MainActivity, .

onCreate , , :

boolean isLoggedIn = checkUserStatus();
Intent intent = isLoggedIn ? new Intent(context, HomeActivity.class) 
                           : new Intent(context, LoginActivity.class);
startActivity(intent);

checkUserStatus() - , , :

protected boolean checkUserStatus(){
    boolean isLoggedIn ;
    Context context = getApplicationContext();
    SharedPreferences pref = context.getSharedPreferences("Session Data", MODE_PRIVATE);
    isLoggedIn = pref.getBoolean("isLoggedIn", false);
    return isLoggedIn ;
}

boolean true false:

SharedPreferences pref = context.getSharedPreferences(
        "Session Data", MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
edit.putInt("LAST_VERSION_CODE", BuildConfig.VERSION_CODE);
edit.putBoolean("isLoggedIn", true);// or false if you log out
edit.commit();
0

All Articles