Vous êtes sur la page 1sur 10

3/16/2014 How to Write an Android App with Activity Lifecycle Function Examples

http://www.thegeekstuff.com/2013/11/write-an-android-app/ 1/10
22 9 Like
Home
Free eBook
Start Here
Contact
About
How to Write an Android App with Activity
Lifecycle Function Examples
by Terrence Sun on November 18, 2013
Tweet 8
Building a basic Android App is relatively easy once you understand the fundamentals.
This tutorial will give you a brief introduction on Android Activity Lifecycle, the files and functions that are involved in
building an Android App.
This should get you started in the right direction and help you to build your own Android app.
I. Android App Files
First, make sure you download and install the ADT Android Developer Tool on you system.
When you create a project (BlankActivity) in ADT, the following 5 files will be created by ADT Blank Activity template
(with Create customer launcher icon and Create activity selected).
1. src/com/projectdomain/appname/
An App must have at least one activity as configured in AndroidManifest.xml file. The main activity exists in
MainActivity.java. The directory hierarchy follows the naming convention of java packages. Project domain can be any
string, but com.example is reserved by Google, and it doesnt allow any public App in Google Play under this name.
Android is designed by keeping multi-language and multi-device support in mind from the very beginning. So, most of
Mobile App Development
clickworkforce.com/Mobile-Apps
For iOs/Android Smartphones & Tabs. We Convert Ideas to Intuitive Apps.
3/16/2014 How to Write an Android App with Activity Lifecycle Function Examples
http://www.thegeekstuff.com/2013/11/write-an-android-app/ 2/10
the resources are mainly described in xml files.
2. res/layout
First of all, we must indicate how the components are laid out on the screen. Since the app may run under various
screen resolutions, more than one layout can be defined. By default, activity_main.xml file is used by MainActivity.java
in onCreate() function.
setContentView(R.layout.activity_main);
If you want to optimize the layout for different screen orientation or size, you should add a new layout directory with
suffix -land and -large. Otherwise, OS will auto-scale and choose the layout.
3. res/values/
Besides layout, the next important thing for GUI is the content displayed to the user. As mention above, in order to
support multiple languages, strings used by the App are all defined in an xml file. By default, there is a strings.xml which
is also used by MainActivity.java
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Test&t;/string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>
If you want to support other languages, add new values directory with suffix -country code, which can be found in ISO
639-1. Android OS will auto-select strings for your locale if available.
Besides strings, you can also use xml files for dimension and style definitions. dimens.xml for dimensions and styles.xml
for styles.
The following code can be found in layout/activity_main.xml file for configuration of padding information.
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
3/16/2014 How to Write an Android App with Activity Lifecycle Function Examples
http://www.thegeekstuff.com/2013/11/write-an-android-app/ 3/10
The following code can be found in AndroidManifest.xml for theme configuration.
android:theme="@style/AppTheme"
4. res/drawable/
This directory stores drawable resources (such as bitmaps and icons). By default, ic_launcher.png file used as icon for
the app.
As for different screen sizes, there are several drawable directories, distinguished by the suffix -xxhdpi, -xhdpi, -hdpi, -
mdpi, and -ldpi. Take mdpi as baseline, xxhdpi has density of 3.0, xhdpi 2.0, hdpi 1.5, and ldpi 0.75.
When referring the resource in code, you dont need to specify the density, as OS will choose the appropriate one
automatically. ldpi can also be left to OS, as 2:1 downscale from hdpi is relatively easy.
5. AndroidManifest.xml
This file defines manifest information for the application which includes permission, broadcast receivers, sdk api level,
etc. all. When adding code that needs extra permission, higher api level, or to receive broadcast message,
corresponding element of this file should also need to be updated.
For ADT, when you are using function that need higher API level, there will be a tip showed near the function call.
II. Android App Activity Lifecycle
An Android Activity has many states in its lifecycle. The following is the Android activity lifecycle sequence.
OS -> Created -> Started -> Resumed -> Paused -> Stopped -> Destroyed
When entering a state, the responding callback function (onStateName) will be called.
Created and Started are transient states which means that App will go to Resumed state without stop. App will be in
Paused state when its partially visible, such as covered by another full screen semi-transparent activity. If the App
occupies the screen again, it will go back to Resumed state. When the App totally goes into the background (not visible
to user), it will go into Stopped state.
So we can add the first loop denoted by () into the lifecycle as shown below.
OS -> Created -> Started -> (Resumed -> Paused) -> Stopped -> Destroyed
For better response, Android will not be so tight on destroying the App instance, so when loosing focus (when user is in
other activity/app), the App will go into Paused or Stopped state. In another words, activity goes to Stopped state,
when its focus is interrupted by other activity. This is not a big issue as the onboard memory of mobile devices are
getting bigger and bigger. When user is back on the activity again, it goes into Started state and then to Resumed state.
Different from the first launch, there is no Created state this time, but an extra OnRestart will be called.
So we can add a second loop denoted by [] into the lifecycle as shown below.
OS -> Created -> [Started -> (Resumed -> Paused) -> Stopped] -> Destroyed
The second loop takes place when user re-entered the app by using Launch icon or Recent Apps, or foreground
3/16/2014 How to Write an Android App with Activity Lifecycle Function Examples
http://www.thegeekstuff.com/2013/11/write-an-android-app/ 4/10
activity ends and makes the stopped activity foreground.
In Destroyed state, the instance is destroyed completely. Usually, as long as there is enough memory, the instance will
be kept in memory in Stopped state. When OS decides to grab more resources, the Stopped instance maybe killed.
But Android cannot guarantee that the onDestroy will be called properly before destroying the instance.
So there is a third loop denoted by {} in OSs view, but it is composed of two different lifecycle for the activity as
shown below.
OS -> {Created -> [Started -> (Resumed -> Paused) -> Stoped] -> Destroyed
-> Created -> [Started -> (Resumed -> Paused) -> Stoped] -> Destroyed}
III. Main Callback Functions
onStart will let LoaderManager to start working, but this stage is not so important to user application. For user
application, onPause and onStop will do most of the cleanup, so most activity does not need to implement the
onDestory method.
The following are the 6 callbacks that are frequently used in an Android App.
1. onCreate(Bundle)
The component and other resources will be created in this function. This is more or less the same for all programs. In
this function, we should make everything ready, and wait to interact (Resumed state) with the user. The Created state
will not stay. So, its not wise to call any working function here. Since GUI is not fully brought up at this stage, most
GUI related function will not work in this state.
By default, only setContentView is called.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
2. onResum
Interaction (such as playing a background music) should start from onResum function. As Resumed state will be entered
multiple times, if object declaration is done in here, do not forget to check the validity of object first.
3. onPause
Pause state indicates that user is not in this App, but user can still see part of this App. So, in this function, stop the
interaction with user, and release resources (such as audio, video) for other Apps to access.
4. onStop
The function will be called when the user is about to completely leave the App. Resource release and state saving
operation (such as saving draft to a file) could be done in this function.
Please keep in mind that when an activity is self-finished or destroyed, such as Back is pressed or finish() is called,
3/16/2014 How to Write an Android App with Activity Lifecycle Function Examples
http://www.thegeekstuff.com/2013/11/write-an-android-app/ 5/10
22 Tweet 8
9 Like
nothing will be left. But, OS may kill/destroy the instance. So, besides saving the working state, other data used in UI
should also be saved here, such as text in a EditView, progress of video playback, etc.
5. onSaveInstanceState(Bundle savedInstanceState)
For View object, OS will help to save it for us, but for Application specified information, it is developers job to save
those. onSaveInstanceState and onRestoreInstanceState are used for this purpose
Extra information should be saved here, which is called before entering the Destroyed state. We can put all necessary
variables to the Bundle, so we dont forgot what we are doing.
6. onRestoreInstanceState(Bundle outState)
We can retrieve the stored variables from Bundle either in onRestoreInstanceState or onCreate.
Note that, when user rotates the screen, destroy and create state sequence will be triggered. If rotation is enabled, these
two function (5, and 6) must be implemented, so that user will continue do what he is doing after the rotation. Callback
function 2-6 are not implemented by default, it can be added by ADT -> Source -> Override/Implement Methods.
> Add your comment
Linux provides several powerful administrative tools and utilities which will help you to
manage your systems effectively. If you dont know what these tools are and how to use them, you could be spending
lot of time trying to perform even the basic administrative tasks. The focus of this course is to help you understand
system administration tools, which will help you to become an effective Linux system administrator.
Get the Linux Sysadmin Course Now!
If you enjoyed this article, you might also like..
1. 50 Linux Sysadmin Tutorials
2. 50 Most Frequently Used Linux Commands (With
Examples)
3. Top 25 Best Linux Performance Monitoring and
Debugging Tools
4. Mommy, I found it! 15 Practical Linux Find
Command Examples
5. Linux 101 Hacks 2nd Edition eBook
Awk Introduction 7 Awk Print Examples
Advanced Sed Substitution Examples
8 Essential Vim Editor Navigation Fundamentals
25 Most Frequently Used Linux IPTables Rules
Examples
Turbocharge PuTTY with 12 Powerful Add-
Ons
3/16/2014 How to Write an Android App with Activity Lifecycle Function Examples
http://www.thegeekstuff.com/2013/11/write-an-android-app/ 6/10
{ 3 comments read them below or add one }
1 Navis Michael Bearly. J November 19, 2013 at 1:10 am
Is it common to all android versions of development.
2 Jalal Hajigholamali November 19, 2013 at 1:22 am
Hi,
Good article, Thanks a lot
3 Guruprasad December 3, 2013 at 12:53 pm
Sir,
The article is really good.
I request you to provide more articles on Android app from you.
Regards,
Guru.
Leave a Comment
Name
E-mail
Website
Notify me of followup comments via e-mail
3/16/2014 How to Write an Android App with Activity Lifecycle Function Examples
http://www.thegeekstuff.com/2013/11/write-an-android-app/ 7/10
Submit
Previous post: What are Linux Processes, Threads, Light Weight Processes, and Process State
Next post: Nginx Vs Apache: Nginx Basic Architecture and Scalability
RSS | Email | Twitter | Facebook | Google+
Search

COURSE
Linux Sysadmin CentOS 6 Course - Master the Tools, Configure it Right, and be Lazy
EBOOKS
Linux 101 Hacks 2nd Edition eBook - Practical Examples to Build a Strong Foundation in Linux
Bash 101 Hacks eBook - Take Control of Your Bash Command Line and Shell Scripting
Sed and Awk 101 Hacks eBook - Enhance Your UNIX / Linux Life with Sed and Awk
Vim 101 Hacks eBook - Practical Examples for Becoming Fast and Productive in Vim Editor
Nagios Core 3 eBook - Monitor Everything, Be Proactive, and Sleep Well
The Geek Stuff
4,816 people like The Geek Stuf f .
Facebook social plugin
Like
3/16/2014 How to Write an Android App with Activity Lifecycle Function Examples
http://www.thegeekstuff.com/2013/11/write-an-android-app/ 8/10
POPULAR POSTS
12 Amazing and Essential Linux Books To Enrich Your Brain and Library
50 UNIX / Linux Sysadmin Tutorials
50 Most Frequently Used UNIX / Linux Commands (With Examples)
How To Be Productive and Get Things Done Using GTD
30 Things To Do When you are Bored and have a Computer
Linux Directory Structure (File System Structure) Explained with Examples
Linux Crontab: 15 Awesome Cron Job Examples
Get a Grip on the Grep! 15 Practical Grep Command Examples
Unix LS Command: 15 Practical Examples
15 Examples To Master Linux Command Line History
Top 10 Open Source Bug Tracking System
Vi and Vim Macro Tutorial: How To Record and Play
Mommy, I found it! -- 15 Practical Linux Find Command Examples
15 Awesome Gmail Tips and Tricks
15 Awesome Google Search Tips and Tricks
RAID 0, RAID 1, RAID 5, RAID 10 Explained with Diagrams
Can You Top This? 15 Practical Linux Top Command Examples
Top 5 Best System Monitoring Tools
Top 5 Best Linux OS Distributions
How To Monitor Remote Linux Host using Nagios 3.0
Awk Introduction Tutorial 7 Awk Print Examples
How to Backup Linux? 15 rsync Command Examples
The Ultimate Wget Download Guide With 15 Awesome Examples
Top 5 Best Linux Text Editors
Packet Analyzer: 15 TCPDUMP Command Examples
The Ultimate Bash Array Tutorial with 15 Examples
3 Steps to Perform SSH Login Without Password Using ssh-keygen & ssh-copy-id
Unix Sed Tutorial: Advanced Sed Substitution Examples
UNIX / Linux: 10 Netstat Command Examples
The Ultimate Guide for Creating Strong Passwords
6 Steps to Secure Your Home Wireless Network
Turbocharge PuTTY with 12 Powerful Add-Ons
CATEGORIES
Linux Tutorials
Vim Editor
Sed Scripting
Awk Scripting
Bash Shell Scripting
Nagios Monitoring
OpenSSH
IPTables Firewall
Apache Web Server
MySQL Database
Perl Programming
3/16/2014 How to Write an Android App with Activity Lifecycle Function Examples
http://www.thegeekstuff.com/2013/11/write-an-android-app/ 9/10
Google Tutorials
Ubuntu Tutorials
PostgreSQL DB
Hello World Examples
C Programming
C++ Programming
DELL Server Tutorials
Oracle Database
VMware Tutorials
Ramesh Natarajan
Follow
About The Geek Stuff
My name is Ramesh Natarajan. I will be posting instruction guides, how-to, troubleshooting
tips and tricks on Linux, database, hardware, security and web. My focus is to write articles that will either teach
you or help you resolve a problem. Read more about Ramesh Natarajan and the blog.
Support Us
Support this blog by purchasing one of my ebooks.
Bash 101 Hacks eBook
Sed and Awk 101 Hacks eBook
Vim 101 Hacks eBook
Nagios Core 3 eBook
Contact Us
Email Me : Use this Contact Form to get in touch me with your comments, questions or suggestions about this
site. You can also simply drop me a line to say hello!.
Follow us on Google+
3/16/2014 How to Write an Android App with Activity Lifecycle Function Examples
http://www.thegeekstuff.com/2013/11/write-an-android-app/ 10/10
Follow us on Twitter
Become a fan on Facebook
Copyright 20082014 Ramesh Natarajan. All rights reserved | Terms of Service

Vous aimerez peut-être aussi