Search code examples
androidandroid-activity

Android Activity Stack Manipulation


I have activity A and B. A is the activity that loads when the app is launched and when they click a button a new intent is made to go to activity B. When I click a button in B I want to put activity A on the top of the stack so when I click the activity A button again it loads my onResume() for activity B instead of my onCreate().

How would I do this?


Solution

  • You could use intent flags to achieve this

    FLAG_ACTIVITY_CLEAR_TOP is the best option here. 
    

    As per the developer site

    If the activity being started is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it are destroyed and this intent is delivered to the resumed instance of the activity (now on top), through onNewIntent()).

    Example of how you set FLAG_ACTIVITY_CLEAR_TOP

      findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Main3Activity.this, Main2Activity.class);
                i.putExtra("HELLO","HI");
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
                        Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(i);
            }
        });
    

    In receiving activity

      @Override
        protected void onNewIntent(Intent intent) {
            super.onNewIntent(intent);
            Toast.makeText(getApplicationContext(), intent.getExtras().get("HELLO").toString(), Toast.LENGTH_SHORT).show();
    
        }