Sunday, November 6, 2016

Understanding Launch Modes in Android

What is Launch Mode?

Launch mode defines how a new instance of an activity associated with the current task(Task is a collection of activities that users interact to perform the certain job).
Launch Mode with example

Types of Launch Mode

  1. Standard (Default launch mode)
    <activity android:launchMode="standard"/>

Standard launch mode is the default launch mode for all activities defined in the android manifest file. In this mode each time we call the new activity through startActivity(intent) it will create a new instance of that activity within the current task. So multiple instances of same activity will be created within the current task

Standard Launch Mode

  1. SingleTop

<activity android:launchMode="singleTop"/>

         If activity instance already exists on top of the stack then no new instance will be created.New instance only will be created if activity A is called by activity B and no new instance of B is yet created in the task or present at any other position other than the top. Refer below image.

SingleTop Launch Mode

Let's understand with the example there is a login activity and home screen. After login, the home screen will be launched now if the user receives a push notification and on tapping the notification home screen will going to be launched. So now as home screen instance already exists we should not create another instance of it rather declare home screen activity as singletop so no new instance will create if it's present on top of the stack. The user can override onNewIntent() method to perform any action if he wants to perform on opening existing instance from notification.

  1. SingleTask
<activity android:launchMode="singleTask"/>
The system creates a new task and pushes the activity at the root of the task. If activity A instance exists in the task stack and if it's called by any other activity lets say D then no new instance of activity A will create rather activities above A will be cleared from task stack and activity A will now be at the top. Refer below image

SingleTask Launch Mode

  1. SingleInstance
<activity android:launchMode="singleInstance"/>
It's same as singleTask only difference is no new activity will be pushed to the task holding singleInstance activity.
SingleInstance Launch Mode

Thanks for reading my first article :)