Search code examples
androidandroid-activityback-stack

How to start the activity that is last opened when launch an application?


I designed an app with several activities. There is only an activity instance in the back stack at any time. When I quit the application from an activity named AcitivityOne, how could I launch the application with ActivityOne next time?


Solution

  • The fast method, is that in your onCreate() put those flags after setContentView():

    if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { 
        finish(); 
        return; 
    } 
    

    Also you can create a SharedPreferences with the Activity last oppened as follows :

    Modify your onPause() to this :

    @Override
    protected void onPause() {
      super.onPause();
      SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE);
      Editor editor = prefs.edit();
      editor.putString("lastopened", getClass().getName());
      editor.commit();
    }
    

    And then in your onCreate() again you put this :

    Class<?> LastOpened;
    
        try {
            SharedPreferences prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
            LastOpened= Class.forName(prefs.getString("lastoppened", MainActivity.class.getName()));
        } catch(ClassNotFoundException ex) {
            LastOpened= MainActivity.class;
        }
    
        startActivity(new Intent(this, LastOpened));
    

    If it doesn't help take a look at this thread