Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 14

Activity Lifecycle

Discipline of IT
James Cook University
Life cycles
• Each android App component has an associated
life-cycle
– Methods that are called at different times while
the component runs

• E.g. Activities have:


– onCreate()
– onStart()
– onStop()
– onRestart()
– onPause()
– onDestroy()
Activity Lifecycle

Get familiar with this!


onCreate() and onDestroy()
• The places to setup and teardown the support
objects and resources

• The view hierarchy is setup in onCreate()

• You setup event handlers in onCreate()

• onCreate() is called once when the Activity is first


created

• onDestroy() is called after the Activity has stopped


working and no longer visible
onStart() and onStop()
• onStart() is called when the activity’s view becomes
visible

• onStop() is called when the activity’s view is not


longer visible
onPause() and onResume()
• onPause() is called when the activity is not
interacting with the user (e.g. a second activity
becomes visible)

• onResume() is called when user interaction returns


to the activity
onRestart()
• Only called if the activity is coming back from being
in the background and no interaction

• Called just before onStart()


Useful callbacks for you…
• onCreate() / onDestroy()

• onPause() / onResume()
The bundle object, and state saving
• There are two more useful methods
– onSaveInstanceState()
– onRestoreInstanceState() / onCreate()

• Very useful for saving user input when the user


moves between Apps
– Making your app move in and out of the
foreground

• Best-practice: save non-model state information


using these methods
Beware: changing the orientation of the device can force an
Activity to be destroyed!

• So if you want to maintain the appears to the user


that the Activity did not stop and restart…
– You need to use the state instance methods!

• It’s important not to try and make a record of


Activity instances – the Android OS will
create/destroy them out of your control!
Suggestions for “well-behaved” apps
• Understand the lifecycle methods of each android
component (Activity, Service, …)

• An indicator of good design is:


– Minimal life cycle management in your code

• Why does Android have these life cycles?


– Because a mobile device is limited
» Battery, memory, CPU, …
The Application Class
• This is a useful place to setup model objects that
are needed across many activities in your App!

• To use a custom Application object


– You need refer to it in the App manifest
To access the Application object from anywhere…

getApplicationContext();

getApplication();

Although…. Google discourages this practice


They suggest using the SINGLETON pattern
Summary
• App lifecycles are a crucial part of any App

You might also like