Search code examples
androidandroid-intentandroid-activityback-stack

Clear Activity back stack


I start from activity A->B->C->D->E ..when i go from D->E there should be no activity in stack but, the user can use back button from D and go to C (without refreshing Activity C, like normal back function)


Solution

  • You could add a BroadcastReceiver in all activities you want to close (A, B, C, D):

    public class MyActivity extends Activity {
        private FinishReceiver finishReceiver;
        private static final String ACTION_FINISH = 
               "com.mypackage.MyActivity.ACTION_FINISH";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            finishReceiver= new FinishReceiver();
            registerReceiver(finishReceiver, new IntentFilter(ACTION_FINISH));
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
    
            unregisterReceiver(finishReceiver);
        }
    
        private final class FinishReceiver extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(ACTION_FINISH)) 
                    finish();
            }
        }
    }
    

    ... and close them by calling ...

    sendBroadcast(new Intent(ACTION_FINISH));
    

    ... in activity E. Check this nice example too.