I need to replace the current activity with a new one. That is, I want to start a new activity and remove the current activity from the task stack.
Based on the documentation, it seems the best way would be to start the activity using Activity.startActivity as per usual, and then call Activity.finish immediately to close the current activity.
Is this a valid usage of these APIs or should I be doing something else?
Android activities are stored in the activity stack. Going back to a previous activity could mean two things. You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.
On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.
Yes. It is fine to use api this way.
The proper way to achieve this is using the following:
Intent intent = new Intent(this,MyActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME); startActivity(intent); this.finish();
The code assumes you are in an activity, otherwise if you are using fragments use getActivity()
This way, the activity is started, you properly set your hierarchy for your back button, and you also destroy the appropriate activity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With