This decision works fine:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
But new activity launch long and you see white screen some time. If this is critical then use this workaround:
public class BaseActivity extends AppCompatActivity {
private static final String ACTION_FINISH = "action_finish";
private BroadcastReceiver finisBroadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(finisBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
finish();
}
}, new IntentFilter(ACTION_FINISH));
}
public void clearBackStack() {
sendBroadcast(new Intent(ACTION_FINISH));
}
@Override
protected void onDestroy() {
unregisterReceiver(finisBroadcastReceiver);
super.onDestroy();
}
}
How use it:
public class ActivityA extends BaseActivity {
// Click any button
public void startActivityB() {
startActivity(new Intent(this, ActivityB.class));
clearBackStack();
}
}
Disadvantage: all activities that must be closed on the stack must extends BaseActivity