Handle the closing of an App on Android

1

I would like that when closing my application in the background, for example when making the swipe as in the following image:

And later that when re-entering the application, it will continue with the active user session and leave me in the Activity that I was last time before closing it.

Currently closing and re-entering leaves me in the initial Activity and I must re-login.

Thanks in advance.

    
asked by Didier 09.05.2017 в 02:18
source

2 answers

2

What you are doing is completely eliminating the execution of the application in memory, therefore when you start it will open with its initial state.  If you want to save the status, you should save some values using some storage method (database, preferences, files), but you should consider that if you want to save a session depending on how sensitive your credential information is, you could even consider saving the session through a webservice.

This is a simple example where using the value of a preference determines that you open at the beginning of the application, the screen to authenticate or the main screen of the application when you have credentials:

//Obtiene valor de sesion activa.
boolean sesionActiva = obtieneValorSesion(getApplicationContext());

//Valida si muestra pantalla de Login o MainActivity desde una Splash Activity.
if(sesionActiva){ 
  //Abre pantalla principal.
  Intent myIntent = new Intent(SplashActivity.this, MainActivity.class);
  startActivity(myIntent);      
}else{
  //Abre pantalla para autenticarse.
  Intent myIntent = new Intent(SplashActivity.this, LoginActivity.class);
  startActivity(myIntent);
}

The methods required to save the value of the session would be:

private String PREFS_KEY = "mispreferencias";

public void guardaValorSesion(Context context, Boolean valorsesion) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
    SharedPreferences.Editor editor;
    editor = settings.edit();
    editor.putBoolean("sesion", valorsesion);
    editor.commit();
}

public boolean obtieneValorSesion(Context context) {
    SharedPreferences preferences = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
    return  preferences.getBoolean("sesion", false); //valor default false
}
    
answered by 09.05.2017 / 17:01
source
1

If you want to persist the status of your activities, you can review the life cycle of Activity .

  • Implement the persistence of your activity status in onStop() or onPause() .
  • Implement state rebuild in onStart() or onPause() .

So you stay with an application that keeps your data independent if it is interrupted by another activity, closed by the user or deleted by memory usage.

    
answered by 09.05.2017 в 03:00