Mono for Android Activity Lifecycle Activity Lifecycle Concepts and Overview

Similar documents
Basics of Android Development 1

An Introduction to Android Application Development. Serdar Akın, Haluk Tüfekçi

ECWM511 MOBILE APPLICATION DEVELOPMENT Lecture 1: Introduction to Android

Introduction to Android: Hello, Android! 26 Mar 2010 CMPT166 Dr. Sean Ho Trinity Western University

Android Application Model

AndroLIFT: A Tool for Android Application Life Cycles

Android Fundamentals 1

INTRODUCTION TO ANDROID CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 11 02/15/2011

App Development for Smart Devices. Lec #2: Android Tools, Building Applications, and Activities

Android For Java Developers. Marko Gargenta Marakana

Mobile Security - Tutorial 1. Beginning Advanced Android Development Brian Ricks Fall 2014

Detecting privacy leaks in Android Apps

Introduction to Android. CSG250 Wireless Networks Fall, 2008

Android Development. Marc Mc Loughlin

Android Basics. Xin Yang

06 Team Project: Android Development Crash Course; Project Introduction

Operating System Support for Inter-Application Monitoring in Android

How to develop your own app

Frameworks & Android. Programmeertechnieken, Tim Cocx

Android Application Development

A Short Introduction to Android

Mobile Application Development Android

Mobile App Sensor Documentation (English Version)

Android Java Live and In Action

Measuring The End-to-End Value Of Your App. Neil Rhodes: Tech Lead, Mobile Analytics Nick Mihailovski: Developer Programs Engineer

App Development for Smart Devices. Lec #4: Files, Saving State, and Preferences

Game Center Programming Guide

Introduction to Android Development. Jeff Avery CS349, Mar 2013

Android Studio Application Development

Q1. What method you should override to use Android menu system?

Android Development Exercises Version Hands On Exercises for. Android Development. v

Graduate presentation for CSCI By Janakiram Vantipalli ( Janakiram.vantipalli@colorado.edu )

Tablets in Data Acquisition

Praktikum Entwicklung Mediensysteme (für Master)

Internet Explorer 7. Getting Started The Internet Explorer Window. Tabs NEW! Working with the Tab Row. Microsoft QUICK Source

Sendspace Wizard Desktop Tool Step-By-Step Guide

Università Degli Studi di Parma. Distributed Systems Group. Android Development. Lecture 2 Android Platform. Marco Picone

Entering Tizen world for ios & Android developers. Cheng Luo, DukSu Han Samsung Platform Evangelist

Android Application Development - Exam Sample

A model driven approach for Android applications development

Mobile Application Development 2014

Using the VMRC Plug-In: Startup, Invoking Methods, and Shutdown on page 4

Getting Started with Android Programming (5 days) with Android 4.3 Jelly Bean

DVR GUIDE. Using your DVR/Multi-Room DVR WAVE-123 wavebroadband.com

Nintex Workflow for Project Server 2010 Help

Android Security Lab WS 2014/15 Lab 1: Android Application Programming

Mobile Applications Grzegorz Budzyń Lecture. 2: Android Applications

Lenovo Miix 2 8. User Guide. Read the safety notices and important tips in the included manuals before using your computer.

Scheduling Guide Revised August 30, 2010

Now that we have the Android SDK, Eclipse and Phones all ready to go we can jump into actual Android development.

3. Add and delete a cover page...7 Add a cover page... 7 Delete a cover page... 7

Kentico CMS 7.0 E-commerce Guide

Building Your First App

Salesforce Classic Guide for iphone

Developing NFC Applications on the Android Platform. The Definitive Resource

Frequently Asked Questions: Cisco Jabber 9.x for Android

Getting Started: Creating a Simple App

Login with Amazon Getting Started Guide for Android. Version 2.0

MA-WA1920: Enterprise iphone and ipad Programming

End User Guide. July 22, 2015

ELET4133: Embedded Systems. Topic 15 Sensors

SoftRAID 5 QUICK START GUIDE. for OWC ThunderBay

Software. Webroot. Spy Sweeper. User Guide. for. Webroot Software, Inc. PO Box Boulder, CO Version 6.

Xamarin Cross-platform Application Development

ANDROID PROGRAMMING - INTRODUCTION. Roberto Beraldi

Xamarin Android Application Development

Creating a Windows Service using SAS 9 and VB.NET David Bosak, COMSYS, Kalamazoo, MI

DEVELOPING DATA PROVIDERS FOR NEEDFORTRADE STUDIO PLATFORM DATA PROVIDER TYPES

How To Develop Android On Your Computer Or Tablet Or Phone

SNMP-NET Client Shutdown Management Software for Windows 2000/XP/2003 User s Manual

InsightPower Client. Shutdown Management Software for Windows 2000/XP/2003. User s Manual

Chapter 2 Getting Started

آموزش DataGrid در WPF به همراه صفحه بندي و جستجوي انتخابی. کلیک کن

Lecture 1 Introduction to Android

Contents of the Guide

Windows XP Pro: Basics 1

By sending messages into a queue, we can time these messages to exit the cue and call specific functions.

Android Developer Fundamental 1

Enhancing Mobile Development with Klocwork Checkers for Android

Creating a 2D Game Engine for Android OS. Introduction

Online Sharing User Manual

Windows 7: Desktop. Personalization

Android Application Development: Hands- On. Dr. Jogesh K. Muppala

g!mobile 6 Android App Android 4.0 or above -- See Android Devices table for compatibility information Document Revision Date: 2/14/2013

Objective. Android Sensors. Sensor Manager Sensor Types Examples. Page 2

IT Quick Reference Guides Using Windows 7

IOIO for Android Beginners Guide Introduction

Transcription:

Mono for Android Lifecycle Lifecycle Concepts and Overview Xamarin Inc.

BRIEF Overview Activities are a fundamental building block of Android Applications and they can exist in a number of different states. The activity lifecycle begins with instantiation and ends with destruction, and includes many states in between. When an activity changes state, the appropriate lifecycle event method is called, notifying the activity of the impending state change and allowing it to execute code in order to adapt to that change. This article examines the lifecycle of activities and explains the responsibility that an activity has during each of these state changes in order to be part of a well-behaved, reliable application. Related Articles: Android.App. Class Android.Content.Intent Class Android.Content.Context Class Related Android Documentation: Android Class Android Intent Class Android Context Class Activities are an unusual programming concept specific to Android. In traditional application development there is usually a static main method, which is executed to launch the application. With Android, however, things are different; Android applications can be launched via any registered activity within an application. In practice, most applications will only have a specific activity that is specified as the application entry point. However, if an application crashes, or is terminated by the OS, the OS can try to restart the application at the last open activity or anywhere else within the previous activity stack. Additionally, the OS may pause activities when they re not active, and reclaim them if it is low on memory. Careful consideration must be made to allow the application to correctly restore its state in the event that an activity is restarted and in case that activity depends on data from previous activities. The activity lifecycle is a collection of methods the OS calls throughout the lifecycle of an activity. These methods allow developers to implement the functionality that is necessary to satisfy the state and resource management requirements of their applications. It is extremely important for the application developer to analyze the requirements of each activity to determine which methods exposed by the activity lifecycle need to be implemented. Failure to do this can result in application instability, crashes, resource bloat, and possibly even underlying OS instability. This article examines the activity lifecycle in detail, including: è States è Lifecycle Methods è Lifecycle Best Practices

Lifecycle The Android activity lifecycle comprises a collection of methods exposed within the class that provide the developer with a resource management framework. This framework allows implementers to meet the unique state management requirements of each activity within an application. The activity lifecycle thus assists the developer by providing a consistent framework in which to handle resource management within the application. States The Android OS uses a priority queue to assist in managing activities running on the device. Based on the state a particular Android activity is in, it will be assigned a certain priority within the OS. This priority system helps Android identify activities that are no longer in use, allowing the OS to reclaim memory and resources. The following diagram illustrates the states an activity can go through, during its lifetime: Starts Running Process Killed Paused Process Asleep Stopped Shut Down These states can be broken into 3 main groups as follows: è Active or Running - Activities are considered active or running if they are in the foreground, also known as the top of the activity stack. This is considered the highest priority activity in the Android stack, and as such will only be killed by the OS in extreme situations, such as if the activity tries to use more memory than is available on the device as this could cause the UI to become unresponsive. è Paused - When the device goes to sleep, or an activity is still visible but partially hidden by a new, non-full-sized or transparent activity, the activity is considered paused. Paused activities are still alive, that is, they maintain all state and member information, and remain attached to the window manager. This is considered to be the second highest priority activity in the Android stack and, as such, will only be killed by the OS if killing this activity will satisfy the resource requirements needed to keep the Active/Running stable and responsive. è Stopped - Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to

be the lowest priority of the three states and, as such, the OS will kill activities in this state first to satisfy the resource requirements of higher priority activities. Multitasking and the Lifecycle UI and multitasking functionality behaves differently in Android than on other mobile platforms. In Android, if a user navigates backwards using the back button on a device, this means that an activity has been navigated away from and the OS will then destroy that activity and reclaim its resources. To use the multitasking capabilities of the operating system (for example, switch foreground applications), the user must press the home key to put their currently executing activity into the background. When this occurs, activities and their resources will be reclaimed, based on the operating system s resource management heuristics triggered by the activity state condition (as described earlier). Lifecycle Methods The Android SDK and, by extension, the Mono for Android framework provide a powerful model for managing the state of activities within an application. When an activity s state is changing, the activity is notified by the OS, which calls specific methods on that activity. The following diagram illustrates those methods and their names:

As a developer, you can handle state changes by overriding these methods within an activity. OnCreate This method is called when the activity is first created. An activity should override this method to setup its main content view and perform any other initial setup, such as creating views, binding data to lists, etc. This method also provides an activity with a Bundle parameter, which is a dictionary for storing and passing state information and objects between activities. If the bundle is non-null, this indicates the activity is resuming and can be rehydrated. Activities can also make use of the Extras container of the

Intent object to restore data previously saved, or data that is being passed between activities. For example, the following code illustrates how to retrieve values from the bundle, and also how to retrieve values from the Extras container: protected override void OnCreate(Bundle bundle) { base.oncreate(bundle); string intentstring; bool intentbool; string extrastring; bool extrabool; if (bundle!= null) { //if the activity is being resumed... intentstring = bundle.getstring("mystring"); intentbool = bundle.getboolean("mybool"); } //Check for the values in the Intent Extras... extrastring = Intent.GetStringExtra("myString"); extrabool = Intent.GetBooleanExtra("myBool", false); } // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); OnStart This method is called when the activity is about to become visible to the user. Activities should override this method if they need to perform any specific tasks right before an activity becomes visible, such as: refreshing current values of views within the activity, or ramping up frame rates (a common task in game building). OnPause This method is called when the system is about to put the activity into the background. Activities must override this method if they need to commit unsaved changes to persistent data, destroy or cleanup other objects consuming resources, or ramp down frame rates, etc. Implementations of this method should return as quickly as possible, as no successive activity will be resumed until this method returns. The following example illustrates how to override the OnPause method to save data in the Extras container, to enable the data to be passed between activities: protected override void OnPause() { Intent.PutExtra("myString", "Hello Mono For Android OnPause"); Intent.PutExtra("myBool", true); } base.onpause();

OnResume This method is called when the activity will start interacting with the user after being in a pause state. When this method is called, the activity is moving to the top of the activity stack, and it is receiving user input. Activities can override this method if they need to perform any tasks after the activity begins accepting user input. OnStop This method is called when the activity is no longer visible to the user, because another activity has been resumed or started and is covering this one. This can happen because the activity is completing (Finish method was called) because the system is destroying this instance of the activity to save resources, or because an orientation change has occurred for the device. You can distinguish between these two scenarios by using the IsFinishing property. An activity should override this method if it needs to perform any specific tasks before it is destroyed, or if it s about to initiate a UI rebuild after an orientation change. OnRestart This method is called after your activity has been stopped, prior to it being started again. This method is always followed by OnStart. An activity should override OnRestart if it needs to perform any tasks immediately before OnStart is called. For instance, if the activity has previously been sent to the background and OnStop has been called, but the activity s process has not yet been destroyed by the OS, then the OnRestart method should be overridden. A good example of this would be when the user presses the home button while on an activity in the application. The OnPause, and then the OnStop methods are called, but the activity is not destroyed. If the user were then to restore the application by using the task manager or a similar application, the OnRestart method of the activity would be called by the OS, during the activities reactivation. OnDestroy This is the final method that is called on an activity before it s destroyed. After this method is called, your activity will be killed and purged from the resource pools of the device. The OS will permanently destroy the state data of an activity after this method runs, so an activity should override this method as a final means to save state data. OnSaveInstanceState This method is provided by the Android activity lifecycle framework to give an activity the opportunity to save its data when a change occurs, for example, a screen orientation change. The following code illustrates how activities can override the OnSaveInstanceState method to save data for rehydration when the OnCreate method is called: protected override void OnSaveInstanceState(Bundle outstate) { outstate.putstring("mystring", "Hello Mono for Android OnSaveInstanceState"); outstate.putboolean("mybool", true);

} base.onsaveinstancestate(outstate); Summary The Android activity lifecycle provides a powerful framework for state management of activities within an application. This article introduced the different states that an activity can go through during the lifecycle. Next, it explored the different methods exposed by the activity lifecycle, and covered some use cases showing when a developer might want to override these methods. Finally, some sample code was provided that illustrated how to use the provided activity lifecycle methods to take advantage of some of the key state storage features in Android.