onBackPressed() override
-
21-12-2019 - |
Question
This is the structure of my application:
Activity A is a ListViewActivity
with a button to start B activity.
In the B activity after completing a form is there a button to start the C activity.
The C activity save the setting and create a new record to show in A activity. The Button save in C activity launch the A activity.
If the user follow this procedure more than once when he press the back button from the A activity return on the B(without passing through the C because when I started it I set FLAG_ACTIVITY_NO_HISTORY
) and the second time he press back return to A again, and this repeats number of time equal to the number of created records.
Close the app with back button became a long process.
I would like the onBackPressed
from the A activity always close the app.
English is not my language, I hope I was clear.
Solution
Always start your activity A like below
Intent intent = new Intent(current_activity_context, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
OTHER TIPS
The method finish() will do that. Something like this
Intent intent = new Intent(getApplicationContext(),
Activity B.class);
Activity A.this.startActivity(intent);
finish();
You must override the OnBackPressed method
@Override
public void OnBackPressed(){
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
super.onBackPressed();//Optional
}
Hope it helps.
try this
@Override
public void onBackPressed() {
// Do Here what ever you want do on back press;
}