Mastering Cross:Platform Development with Xamarin
上QQ阅读APP看书,第一时间看更新

Chapter 2. Memory Management

This chapter investigates how memory is managed on iOS and Android with Xamarin runtime. Whilst drawing parallels to the .NET platform, it will provide examples of memory management problems and issues that can cause leaks, and also look at useful patterns that can help developers save valuable resources. This chapter is pided into the following sections:

  • Application Component lifecycle
  • Garbage collection
  • Platform-specific concepts
  • Troubleshooting and diagnosis
  • Patterns and best practices

Application Component lifecycle

Each platform in the Xamarin ecosystem has certain processes and states that the applications go through during their execution lifetime. Developers can implement certain methods and subscribe to lifecycle events such as application start, suspension, termination, and backgrounding to handle much needed application state and release resources which are no longer required.

Activity lifecycle (Android)

In Android applications, contrary to the conventional application development model, any activity can be the access point to the application (as long as it is designated as such). Any activity in the application can be initialized at start-up or can be resumed directly when the application is resuming or restarting from a crash.

In order to manage the lifecycle of the activities, there are distinct states and events which help developers organize memory resources and program features.

Active/Running

An activity is said to be in the active state when an application is the application in focus and the activity is in the foreground. At this state, unless extraordinary measures are required by the operating system (for example, in case of system out of memory or application becoming unresponsive), the developer does not need to worry about the memory and resources, as the application has the highest priority.

In a creation cycle, OnCreate is the first method that is called by the application. This is the initialization step where the views are created, the variables are introduced, and static data resources are loaded.

OnStart or OnRestart (if the activity is restarting after it was backgrounded) is the second event method in a creation cycle. This method(s) can be overridden if specific data reload procedures need to be implemented. This is the last method called before the activity becomes visible.

The OnResume method is called after a successful launch of the activity. This method is the indication that the application is ready for user interaction. It can be used to (re)subscribe to external events, display alerts/user messages, and communicate with device peripherals.

Paused

An activity is paused when either the device goes to sleep having this activity in the foreground, or the activity is partially hidden by another dialog or activity. In this state, the activity is still "alive" but cannot interact with the user.

The OnPause event method is called right before the activity goes into the Paused state. This event method is the ideal place to unsubscribe from any external event providers, commit any unsaved changes and clean up any objects consuming memory resources since the user interaction is not possible in the Paused state. The activity will call only the OnResume method when once again the activity has the highest priority, it will not go through the full creation cycle.

Backgrounded

An activity goes into the Backgrounded state when the user presses the home button or uses the app switcher. In this state, it is not guaranteed that the activity will stay alive until the user "restarts" the application.

The OnStop method is called when the application is backgrounded or stopped. The difference between the Backgrounded and Stopped states is that the activity is in the Stopped state when it is being prepared for destruction and it will be followed by the OnDestroy method since the application is dismissed and will not be used by the user anymore. If the user resumes the application, the activity will call the OnRestart method and a full creation process will follow.

Stopped

The Stopped state represents the end of the lifecycle for the activity. The activity enters this state when the user presses the back button signifying that the application is not needed anymore. However, it is also possible that the activity is taken into this state because the system is starved of memory resources and it needs to take down activities that are on the lower priority states like paused or backgrounded.

The OnDestroy method follows the Stopped state and it is the last lifecycle event method that is called. It is the last chance for the application to stop long running processes that might cause leaks or clean up other persistent resources. It is advisable to implement most of the resource clean up in OnPause and OnStop methods, since OnDestroy can be called unexpectedly by the system contrary to the user initiated OnPause and OnStop methods.

Restarted

An activity is said to be "restarted" when it comes back to user interaction after it was backgrounded. Restarted activities can reload any saved state information and create an uninterrupted user experience. After going through the initialization steps, the application goes into the Running state again.

Application lifecycle (iOS)

On iOS, the application lifecycle is handled through UI application delegates. Once the delegate methods are implemented and registered, the methods will be invoked by the execution context.

public class Application
{
    static void Main(string[] args)
    {
        UIApplication.Main(args, null, "AppDelegate");
    }
}

[Register("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
    //Implement required methods
}

Application events on iOS are a little more complicated than the top-down execution of events on Android. Developers can insert their methods into transitive states using the state-related methods implemented in the AppDelegate.

Figure 1: iOS Application State Transitions

The most important state-related methods are the following:

  • WillFinishLaunching is the first chance of the application to execute code at launch time. It indicates the application has started to launch but the state has not yet been restored.
  • FinishedLaunching is called once the state restoration occurs after the WillFinishLaunching is completed.
  • OnActivated and OnResignActivation are similar to OnPause and OnResume event methods on the Android platform.
  • DidEnterBackground is called when the application enters the Backgrounded state. It is similar to the OnStop method on Android but there is a time constriction on this method; the method should execute in less than 5 seconds, and the method exits without notification after the allocated time. If more time is needed to execute certain methods in this delegate, applications can start a background task to complete the execution.
  • WillEnterForeground and WillTerminate can follow the DidEnterBackground execution. If the former method is called, the application is about to be brought back to foreground and active state, otherwise, the application is prepared to be terminated because the system needs more memory, or the user is closing a backgrounded application.