Can an Activity be saved in a preference?

2

I'm creating an App, I've already finished it, but I start thinking as a user if I'm browsing and suddenly I'm forced to close the App or minimize it, it starts again with the activity that is predetermined in manifest de android , and lost in continuity How could I do to store that activity in memory, and continue where I stay even after closing it or minimizing it?

Many games and applications that offer progression by levels, this usually stays where the user left them.

    
asked by Gean BCone Angulo 06.01.2017 в 23:58
source

1 answer

2

NO , what is done is to save the data in preferences this to generate the Activity again but it is not possible to save an Activity.

What you can do is save the name of Activity in preferences as String and use this to open the Activity in this way:

startActivity(this, Class.forName("<nombre ultima Activity>"));

To save and get the name of the Activity in preferences you can use the methods:

private String PREFS_KEY = "mispreferencias";

public void saveNombreActivityPref(Context context, String nombreActivity) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
    SharedPreferences.Editor editor;
    editor = settings.edit();
    editor.putString("nombreActivity", nombreActivity);
    editor.commit();
}



public String getNombreActivityPref(Context context) {
    SharedPreferences preferences = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
    return  preferences.getString("nombreActivity", "");
}

Save name (you could implement it in the onDestroy () of the Activity):

protected void onDestroy(){
    super.onDestroy();

    //Guarda nombre de Activity.
    saveNombreActivityPref(getApplicationContext(), nombreActivityActual) {

}

gets name and opens Activity :

  //Obtiene nombre.
  String nombreUltimaActivity = getNombreActivityPref(getApplicationContext());
  //Abre Activity.
  startActivity(this, Class.forName(nombreUltimaActivity));
    
answered by 07.01.2017 в 00:31