0

I have 5 activities in my application. On each activity there is a button to take it to the next activity. So the stack of the activity is like :

Activity 1->Activity 2->Activity 3->Activity 4->Activity 5

On the 5th Activity there is a button with which I just want to clear the previous activities. I am not starting any new activity here.

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

It cannot be done with this, because a new activity has be started.

What can be done for this?

WISHY
  • 11,067
  • 25
  • 105
  • 197

2 Answers2

1

I prefer to use EventBus to solve the problems.

The schema:
Each activity which is needed to be close needs to wait for a close event. When button close is clicked, the close event will be sent and every activity waiting for the close event will be closed.

How to achieve:

  1. Make a class for an event for closing activity, CloseEvent. CloseEvent is a simple class:

    public static class CloseEvent{}
    
  2. Register each activity for receiving Event from EventBus.

    @Override
    public void onStart() {
      super.onStart();
      EventBus.getDefault().register(this);
    }
    
    @Override
    public void onDestroy() {
      super.onStop();
      EventBus.getDefault().unregister(this);
    }
    
  3. Subscribe each activity to receive CloseEvent.

    @Subscribe 
    public void onMessageEvent(CourierOrderTimeEvent event) {
      this.finish() // Close the activity.
    }
    
  4. Sent the CloseEvent when the button is clicked.

    button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        EventBus.getDefault().post(new CloseEvent());
      }
    });
    
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
0

instead of using startActivity() you can use startActivityForResult()

suppose from activity1 to activity5 you are lauching activity using startActivityForResult()

   Intent intent = new Intent(Activity1.this, Activity2.class);
    startActivityForResult(intent, 1);



 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, requestCode + "");
        finish();
    }

in Activity2 you can use

startActivityForResult(new Intent(Activity2.this, MainActivity3.class), 2);

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, requestCode + "");
        Intent intent=new Intent();
        setResult(1,intent);
        finish();//finishing activity
    }

like that till activity 4

in Activity 5 when you click button as mention above you can use below code.

Intent intent=new Intent();
setResult(5,intent);

please let me know if are able to solve your problem

Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147