How to always start Login activity whenever app comes to foreground from background?

844 Views Asked by At

I have LoginActivity which is my MAIN as well as LAUNCHER Activity and I also have other activities such as CustomerAddActivity & CustomerListActivity.

Now Suppose I'm in CustomerAddActivity and I pressed Home button and app goes to background and when again app comes to foreground it must have to ask for LoginActivity first if valid credentials(simple credentials such as username and pin from sq-lite) then back to CustomerAddActivity with it's state.

2

There are 2 best solutions below

0
On

When returning to your app you can startActivityForResult to log-in the user and then go back to the previous state. In order to do it from anywhere you can define an abstract BaseActivity like this and override it from all your other classes:

public abstract class BaseActivity extends AppCompatActivity {
    public static final int REQUEST_CODE = 1;
    private boolean shouldCheckCredentials = false;

    @Override
    protected void onPause() {
        shouldCheckCredentials = true;
        super.onPause();
    }

    @Override
    protected void onResume() {
        if(shouldCheckCredentials){
            Intent loginIntent = new Intent(this,LoginActivity.class);
            startActivityForResult(loginIntent,REQUEST_CODE);
        }
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == BaseActivity.REQUEST_CODE && resultCode == RESULT_OK) {
            shouldCheckCredentials = false;
        }
    }
}
0
On

you can pass the login information in the intent when starting CustomerAddActivity from LoginActivity

In LoginActitivity

Intent intent = new Intent(this, CustomerAddActivity.class);
    intent.putExtra("login_info", "success");
    startActivity(intent);

then in onResume () of CustomerAddActivity() remove that login information

 @Override
protected void onResume() {
    super.onResume();

    String login = getIntent().getStringExtra("login_info");
    if(login != null){
        getIntent().removeExtra("login_info"); 

    } else {
        startActivity(new Intent(getApplicationContext(), LoginActivity.class));
    }
}

So whenever your CustomerAddActivity comes to foreground it would first check the login_info. If it couldn't find that it would start the LoginAvctivity.