Thursday, November 6, 2014

Windows Runtime apps Application Life Cycle(Windows Phone 8.1 and windows 8.1)



The application life cycle is a very basic and one the most important concepts that every app developer should know and use the application life cycle events to handle the use case scenarios to give the best possible experience to the user .

If you are a windows phone 8 developer then things have changed here and if you have developed for big windows(windows 8/8.1) then you will feel more at home.

Lets get started .


Image Courtesy: msdn 

Must have seen the above diagram in many  msdn  articles , lets get in to the details .

From the above diagram we have the below list of application states 

  • Running
  • Suspended 
  • NotRunning 

The application is either Running, Suspended or NotRunning .

When do we say the application is running?

When the application in the foreground, and also when the application goes to the background(by pressing the windows key/search key/back key)just before it gets suspended.


When do we say the application is Suspended?

When the user navigates away from your application ,which he can in many ways (by pressing the windows key/search key/back key). and does not return back to the application soon enough(could be between 5 to 10 seconds), the application gets suspended.

 When do we say the application is NotRunning?

  •  If the application is a fresh install (application was never launched).
  •  If the application is closed by the user (using task switcher).
  •  If the application goes into the suspended state , and the OS decides to terminate the application to  give some memory to foreground application.

Now that we know the different application states, lets us see what the OS has to offer to the developers to react to these different states.

Below are the list to events that are available for developers

Now lets go over each of  the application life cycle events .

Application.OnLaunched Event

Usually  this event is fired when the user taps on the primary tile or launches the application from the app list. but need not be the only case , there are several ways by  which an application can be launched ,more on that later.

How does the developer react to this event?

In the app.xaml.cs file you have to override the  Onlaunched  Handler 

 protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
        //
    }

What should the developer do when this event occurs?

In the Onlaunched Handler the developer gets the LaunchActivatedEventArgs object as parameter which holds  vital information like how the application was launched and how was the previous instance of the application exited. using these information  the developer can decide to show the default page of the application or take the user to the page where he was when the application was previously exited.

Check out the below code :
protected override void OnLaunched(LaunchActivatedEventArgs e)
    {

          /*means application is launched by the user 
             by clicking on tile/from app list for the first time */
        if (e.Kind == ActivationKind.Launch && e.PreviousExecutionState == ApplicationExecutionState.NotRunning)
        {
             // and you would want to show the splash screen and take the user to the default screen
        }

             /*means application is launched by the user 
                by clicking on tile/from app list and the previous instance of the  app was closed by the user        */
        if (e.Kind == ActivationKind.Launch && e.PreviousExecutionState == ApplicationExecutionState.ClosedByUser)
        {
            //here based on the developer choice you can either take the user to default screen/restore the previous state 
        }


        /*means application is launched by the user 
           by clicking on tile/from app list and the previous instanse app was terminated by OS to free up memory*/    
        if (e.Kind == ActivationKind.Launch  && e.PreviousExecutionState == ApplicationExecutionState.Terminated )
        {
            /*here the developer would want to take the user to the screen where he left off
              you would want to consider the timespan as well when the app  was suspended,
              because  sometimes if the app was suspended for days , you would want to take the user 
              to the default screen rather than restoring the state.
             *** its totally the developers calls  make sure the user gets the best experiance using the application */
        }

        /* lets say you  app is  music player application  the app is registered to handle the .mp3 file */
            
        if (e.Kind == ActivationKind.File && e.PreviousExecutionState == ApplicationExecutionState.ClosedByUser)
        {
            /* this condition occurs when the application launched by clicking a mp3 file,
              here developer can take appropriate action */
              
        }
}

we just walked through a few combinations of use cases that the developer would generally handle.There are lot more  possible combinations check out ActivationKind enumeration  and ApplicationExecutionState enumeration , use the combination best suited to your needs.

Application.OnActivated Event


This event is fired when the application is not launched by App Contracts and Extensions like  voice command, PickerReturned etc, can find more about it here .

How does the developer react to this event?

In the app.xaml.cs file you have to override the  OnActivated  Handler

 protected override void OnActivated(IActivatedEventArgs args)
    {
           
    }

What should the developer do when this event occurs?

The IActivatedEventArgs object passed as  parameter offers the same  ActivationKind enumeration and ApplicationExecutionState enumeration values and  things can be handled in the exact same way as in OnLaunched Event.

There are contract specific Activation events as well which the developer will have to subscribe for different type of activation of the application.

Application.Suspended  Event


This event occur when the user navigates away from your app by either hitting the windows keys , task switcher or any other way .


What should the developer do when this event occurs?

  • save any unsaved session data of the user so that you can restore them when the user comes back to the application .
  • serialize heavy object and save  to a file , so that you can free up some memory .
  • release the recourse used  (opened file stream / network stream or more).

Please note the application will never receive a termination event, so you should do all the clean up job in this event Handler .


How does the developer react to this event?

In the app.xaml.cs file you can subscribe to the Suspending event in the App constructor or you can also do it at the page level .
 
public App()
    {
      this.InitializeComponent();
      this.Suspending += OnSuspending;
    }

 void OnSuspending(object sender, SuspendingEventArgs e)
    {
      // All your clean up logic here 
    }


OR

public MainPage()
   {
      InitializeComponent();
      Application.Current.Suspending +=
      new SuspendingEventHandler(App_Suspending);
   }

 void OnSuspending(object sender, SuspendingEventArgs e)
    {
      // All your clean up logic here 
    }


If you have any asynchronous operation that needs to be completed before the application is suspended then you will have to defer the suspension till the  async operation is complete.
** the operation still needs to complete within 10 seconds  .

Below is how you do the async operation .
async protected void OnSuspending(object sender, SuspendingEventArgs args)
{
    SuspendingDeferral deferral = args.SuspendingOperation.GetDeferral();
    await SuspensionManager.SaveAsync();
    deferral.Complete();
}

Application.Resuming event


This event occurs when the application comes from suspended state into running state (when user switches back into your application).

What should the developer do when this event occurs?

When the application is resuming from the suspended state, the application data and states are automatically restored as the snap shot of the application is saved by the OS during suspension.
But there are scenarios when you have to handle this resuming state, let me list out a few of them 
  • Timer don't tick when the app is suspended you should handle the timer ticks.
  • you might want to make network calls to show the updated data.
  • you will have to update the location information.

How does the developer react to this event?

In the app.xaml.cs file you can subscribe to the Suspending event in the App constructor or you can also do it at the page level as already shown for suspended event .

public App()
    {
      this.InitializeComponent();
      this.Resuming += OnResuming;
    }

  void OnResuming(object sender, object e)
    {
    }


2 comments:

  1. you wrote so much!!!

    ReplyDelete
  2. Great article... Thanks for sharing. Very important post for me as I try to figure out how the life cycle of Windows Apps is managed.

    ReplyDelete