There are a lot of questions related to back stack management, but none really satisfied me. The closer I found is that one but it looks like an ugly workaround to me.
When clicking on a button in activity A, I'm launching an activity B with startActivityForResult()
, expecting a simple A -> B back stack.
But if you spam the button fast enough, you end up with two intents being fired and thus two activities stacked A -> B -> B.
I tried to use FLAG_ACTIVITY_SINGLE_TOP
flag to prevent the second B activity from being created but it didn't change anything:
This is the button listener in activity A:
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), ActivityB.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityForResult(intent, REQUEST_CODE);
}
});
And logs clearly states that onCreate()
in invoked twice (instead of the expected onNewIntent
):
btn.onClick()
activityB.onCreate()
btn.onClick()
activityB.onCreate()
My activity must not be singleTask
nor singleInstance
, they should just be part of the back stack as any regular activity. Any clearance would be much appreciated!
Your problem is two activity started by you button click spamming.
In a simple way set boolean field to prevent starting two activities.
Example:
boolean isClicked;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!isClicked){
isClicked = true;
//start activity here.
}
}
});
In your onPause()
set the boolean field false.