Newer Post

Droidcon India 2016

Older Post

Hello World

finish() - The right way to finish an activity ?

I thought finishing an activity in Android is a very trivial thing until recently when a colleague at work asked me about the right way to finish an activity. I know what you are wondering -

" The right way to finish an activity ? "

Have a look at this piece of code :

  this.finish(); //Finish the activity
  Intent intent = new Intent(this, MyActivity.class);
  startActivity(intent); // Start new activity

Does that code seem familiar ? We finish the current activity and start a new activity. Simple right ?

The problem

While that piece of code seems to be perfectly normal and will work fine there is a small problem with it. The user sees a black screen momentarily before starting the new activity. This happens because when we finished the activity there was no UI inflated yet to be shown to the user.

Image source : StackOverflow

The solution

The solution is pretty simple, you start the new activity first and then finish the current activity. That will make sure that the user doesn't see the momentary black screen between activity switch. This is what the updated code should look like :

    Intent intent = new Intent(this, MyActivity.class);
    startActivity(intent); //Start new activity
    this.finish(); //Finish the activity



As you can see a simple change in the sequence of finish() call fixes the problem. This might be a trivial thing but makes a huge difference in terms of the user experience. So next time, you are trying to finish an activity, make sure you don't forget to start the new activity first before finishing the current activity.