Learning Android Intents

4 (1 reviews total)
By Muhammad Usama bin Aftab , Wajahat Karim
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Understanding Android

About this book

Android is an emerging technology with loads of apps in the Google Play Market. Till date, it is the biggest marvel in Smartphone technology, propelling a larger number of developers into Android application development. Intent is an essential part of any Android Application and no Android application is complete without using them. Features such as listening broadcasts, sending messages, sharing via social networks, notifications, hardware components including camera, sensors, Wi-Fi, and more, can be used in your applications by using Intents.

This practical guide focuses on using intents to make the best use of various features of Android platform. It is ideal for those developers who want to understand the backbone and the domain of Android Intents, its power, and the need for it inside an Android application. Practical, in-depth examples are used throughout the book, to help you understand the key concepts.

The book starts with introducing the very basic concepts of Android, and its various facts and figures such as different Android versions, their release dates, evolution of Android phones and so on. While covering the basic technical concepts, it proceeds from the easiest route of introducing Android Intents towards the more practical view of Android Intents in terms of components and features.

You will learn how to use different components and features such as transfer data between activities, invoke various features and components of Android, execute different in-built and custom-made services, use hardware and software components of Android device, and start Pending Intents & notifications. You will gain better theoretical knowledge of what is running behind the concepts of Android Intents, and practical knowledge of the mobile-efficient ways to perform a certain task using Android Intents.

Towards the end, you will have a clear vision and a practical grip on Android intents and its features. Learning Android Intents is a proper guide to give you the best knowledge of Intents.

Publication date:
January 2014
Publisher
Packt
Pages
318
ISBN
9781783289639

 

Chapter 1. Understanding Android

This chapter provides you with a strong theoretical concept of Android. It is obvious that the term is not alien even for any novice technology user. Because of the popularity of this great operating system, many developers started to shift from web development and other platforms. This huge migration has brought a significant change in the market of Android apps and has opened new, unlimited doors for new mobile application developers. Android is a strong opponent of iOS which is an operating system by Apple Inc. However, as statistics suggest, Android is catching up with the iOS market in terms of revenue as Google Play is the fastest growing app market in terms of total number of downloads.

This chapter includes the following topics:

  • Introducing Android

  • Understanding the whys and whens of Android

  • Official Google IDE for Android Developers – the Android Studio

  • Structure of an Android application

  • Presenting the Android Activity lifecycle

 

Introducing Android


Android is a Linux-based operating system which makes it an open source software. Google distributed its license under the Apache License Agreement. The availability of Android code makes it an easily-modifiable operating system, which can be customized by the vendor as well. Due to a highly flexible design, some critics call it unsecure, which was right at a certain period of time, but now, Android is a mature operating system with a high-level secure architecture. It is said that the newest version of Android (that is, Jelly Bean) is the most secure operating system that Google has ever produced. Let's move forward with an overview of the different versions of the Android OS.

Exploring the different versions of Android

Since the beginning, Android has been transforming itself with the release of different versions. Not just UI but many features were added, modified, and enhanced in each upcoming version. The first version to officially use the name of a dessert was Android Cupcake 1.5, which was based on Linux 2.6.27. Every new Android version comes with a new set of API levels, which basically revises the previous API with some modification, obsoleteness, and addition of new controls.

Releasing new versions of Android brings some obsoleteness in the previous methods/functions from a developer's point of view. However, this will bring warnings but not errors; you can still use previous method calls in new API Levels as well.

The following table shows the different Android versions with their API Levels and major highlights:

Android version

Version name

Main features

API level

Release date

Android 4.1/4.2/4.3

Jelly Bean

Google Now

Voice-to-search

Lock screen widgets

Speed enhancements

Gesture typing in keyboard

Secure USB debugging (for developers only)

OpenGLES 3.0 support

Improved camera user interface

Right-to-left languages support

16, 17, and 18

July 9, 2012, November 13, 2012, and July 24, 2013

Android 4.0

Ice Cream Sandwich

Major UI changes

Enhanced lock screen actions

Screen orientation animation

Email app with EAS v14

Facial unlock

Enhanced web browser

Support of tablet and cell phones

14 and 15

October 19, 2011

Android 3.x

Honeycomb

First OS for tablets

Addition of system bar and action bar

Quick access to camera and its features

Two pane email UI view

Multi-core support

11, 12, and 13

February 22, 2011

Android 2.3

GingerBread

Enhanced UI

Native VoIP/SIP support

Google Talk and Google Wallet

Video call support

9 and 10

December 6, 2010

Android 2.2

Froyo

Speed improvements

USB tethering

JIT implementation

8

May 20, 2010

Android 2.0/2.1

Eclair

Updated UI

Live wallpaper

Bluetooth 2.1

5, 6, and 7

January 12, 2010

Android 1.6

Donut

Gesture recognition

4

September 15, 2009

Android 1.5

Cupcake

Text prediction in keyboard

Record and watch videos

3

April 30, 2009

Note

It is an interesting fact that the versions of Android are in alphabetical order. Starting off from Apple Pie 1.0 and then Banana Bread 1.1, it made its way towards Jelly Bean with a complete coherence of alphabetical sequence, and by maintaining the legacy; the next version expected will be Key Lime Pie.

As it is mentioned earlier that Android is open for modifications by the vendor due to its open-sourced nature, many famous mobile manufacturers put their own customized versions of Android in their phones. For example, Samsung made a custom touch interface over Android and calls it TouchWiz (Samsung Galaxy S4 comes with TouchWiz Nature UX 2.0). Similarly, HTC and Sony Xperia came up with their own custom user interface and called it HTC Sense and TimeScape respectively.

Google Play – the official app store for Android

Just like any other famous mobile operating systems, Android has its app store known as Google Play. Previously, the app store was called Android Market, which, at the start of the year 2012, became Google Play with a new-and-improved user experience. The update unified the whole entertainment world under the umbrella of Google Play. Music, apps, books, and movies, all became easily accessible to the users just like Apple's famous App Store (iTunes). You can find detailed information about the Android store at http://play.google.com/about/.

Note

Google Movies & TV, Google Music, Google Books, and Google Magazines are only available in limited countries.

Google Play provides a wide range of applications, movies, e-books, and music. Recently, they also introduced the Google Play TV facility under the same app store. Talking about the application side, Google Play provides different categories in which a user can select applications. It ranges from games to comics and social apps. Users can enjoy many paid applications and can unlock many features by in-app billing services provided by Google Play.

There are different vendor specific app stores as well, such as Kindle's Amazon App Store, Nook Store, and many others that provide many applications under their own terms and conditions.

 

Understanding the whys and whens of Android


Android is a Linux-based open source operating system, primarily targeted for touch screen mobiles and tablets. Andy Rubin, Rich Miner, Nick Sears, and Chris White founded the operating system in October 2003. The basic intention behind the idea of Android was to develop an operating system for digital content. This was because, at that time, mobiles were using Symbian and Windows Mobile as their operating systems.

Note

iPhone was released in June 2007 by Apple Inc. Android was released in November 2007 by Google Inc.

However, when they realized that there is not much of a market for devices such as cameras, they diverted their attention to mobile phones against Symbian and Windows Mobile. iPhone was not on the market then. Android Inc., a top brand for smart phone operating systems covering 75 percent of market share as of today in smartphones, was running secretly at that time. They revealed nothing to the market except that they were working on software for mobile phones. That same year, Rubin, the co-founder of Android, ran out of money, and his close friend, Steve Perlman, brought him $10,000 cash in an envelope.

In August 2005, Google Inc. acquired Android Inc., making it a subsidiary of Google Inc. The primary employees of Android stayed in Android Inc. after acquisition. Andy Rubin developed a mobile device platform powered by Linux Kernel. Handset makers and carriers were being promised a flexible and upgradeable operating system by Google. As Google was not releasing any news about Android in the media, rumors started to spread around. Speculations spreading around included Google is developing Google branded handsets and Google is defining cell phone prototypes and technical specifications. These speculations and rumors continued until December 2006.

Later, in November 2007, Open Handset Alliance revealed that their goal was to develop an open standard for mobile devices. Android was released as its first product; a mobile device platform built on Linux Kernel Version 2.6. Open Handset Alliance is a consortium of 65 companies involved in mobile space advocating open source standards for the mobile industry.

In October 2008, the very first commercially available phone deploying Android operating system was released by HTC, called HTC Dream. The following image shows HTC Dream. Since then Android is being upgraded. Google launched its nexus series in 2010.

HTC Dream, the First Android phone using Android Activity back stack

The evolution of Android OS

After the first appearance of Android OS in HTC Dream, it gained rapid popularity among consumers. Android is continuously being upgraded by Google. Each major release includes bug fixes from the last release and new features.

Android released its first version in September 2008 in the device HTC Hero. Android 1.1 was an update tweaking bugs and issues, with no major release. After Android 1.1, Android 1.5 named Cupcake, was released with features such as video uploading, text prediction, and so on. Android 1.6 Donut and Android 2.0/2.1 Éclair released at the end of 2009, followed by 2.1 in January 2010, introduced major updates such as Google Maps, enhanced photo video capabilities, Bluetooth, multi-touch support, live wallpapers, and more. In May 2010, Android 2.2 named as Frozen Yogurt, or Froyo, was the major release, adding support for Wi-Fi hotspot connectivity.

This version became very popular among developers, and is used to be the minimum API level for android apps. Android 2.3 Gingerbread, released in May 2010 introduced the Near Field Communication (NFC) capability, which allowed users to perform tasks such as mobile payments and data exchange. This version of Android became the most popular version among developers. Android 3.0/3.1 Honeycomb, was specially optimized for tablet devices, and more UI control for developers was a big plus. Android 4.0 Ice Cream Sandwich was released in October 2011. Since Android 3.0/3.1 was only for tablets, the Ice Cream Sandwich release overhauled the gap, and was supported by both mobile phones and tablets. The latest release of Android, Android 4.2 Jelly Bean further polished the UI, refined the software, among other improvements.

Note

Google started naming Android versions after sugar treats, in alphabetical order, after Android 1.1 version.

The following image shows all the versions in a visual format:

The following screenshot shows the current distribution (March 2013) of Android versions. It is clear from the screenshot that Android 2.3 Gingerbread is the most popular version, followed by Android Ice Cream 4.0:

Current distributions of Android versions

 

Official IDE from Google – the Android Studio


Before Google I/O 2013, Android was officially using Eclipse as an IDE for its development. Official Android Support clearly mentioned about the use of this IDE along with the Android Development Tools (ADT) and Android Software Development Kit (SDK) with its documentation.

Loading Screen for Android Studio (Windows 7)

In Google I/O 2013, Google came up with a new IDE that is specially designed for the development of Android Apps. The IDE is called Android Studio, which is an IntelliJ-based software that provides promising features to the developers.

Features of Android Studio

Android Studio gives various features on top of an IntelliJ-based IDE. The list of features that are introduced in Android Studio is as follows:

  • Android Studio comes with built-in Android Development Tools

  • Android Studio gives Gradle-based support for the build

  • Flexible controls for building an Android UI and simultaneous views on different screen sizes

  • Android refactoring, quick fixes, and tips and tricks

  • Advance UI maker for Android apps with drag-and-drop functionality

The following screenshot shows the Android Studio multi-screen viewer with UI maker:

Note

The current version of Android Studio is v0.1.1.

Apart from that, there are various other features that are offered by Android Studio. Google mentioned in the launch that the version (v0.1) is unstable and needs various fixes before it can be used with its 100 percent accuracy.

Limitations of Android Studio

Android Studio is in the early phase, which makes it an immature software with limitations. According to Google, they are working on the updates of the software and soon will rectify the issues. As per Version 0.1.1,the limitations faced by the developers are as follows:

  • Android Studio can only be compiled with Android 4.2 Jelly Bean

  • The user interface can only be made with Android 4.2 Jelly Bean UIs and widgets

  • An Eclipse project cannot be directly imported on Android Studio (refer to http://developers.android.com/)

  • Bugs in importing library projects

 

Building blocks of an Android application


An Android application consists of various building blocks that help developers to keep things organized. It gives flexibility to maintain assets, pictures, animations, movie clips, and implement the localization functionality. Moreover, there are some components that contain the information regarding the minimum and maximum versions of Android that your application supports. Similarly, menus are separately handled in Android application projects.

Various components of an Android application as shown in Android Studio

Just like Eclipse IDE, Android Studio gives various handy functionalities to play with these features. Looking forward to the building blocks of the Android application, we can classify the components into the following parts:

  • Coding components

  • Media components

  • XML components

  • Referencing components

  • Library components

Coding components

Breaking into components brings an easy understanding of the structure of an Android application. Coding components are those that directly relate to the source code of an Android project. In order to write an application, a developer needs to write some lines of code that will respond in the way the user wants.

In coding components, the main folder that holds all of the developer's code is src. The folder consists of one or more Java packages in which developers classify their code in accordance with the type of work done. The default way to write a package name is dot separated (for example, com.app.myapplicationproject), which can easily distinguish it from any other package of any other project.

Note

The Android application's package name is used to identify it uniquely on Google Play.

Inside the packages there are .java files that are present for the developer to reference from the Android library and proceed to the desirable output. These Java classes may be or may not be inherited from the Android API. We can also use most of the Java functions in writing our code.

Media components

Due to highly configured hardware, users need applications with good graphics, animations, sounds, and video files. Hence, you can easily introduce any of them but it should be made sure that none of them should affect the quality of the app as there are thousands of different types of Android devices available. Android provides a flexible method that you can use to place your media files within the project. By classification, there are two ways of maintaining your media files inside an application project:

  • Assets folder

  • Res folder

The assets folder

An Android project contains a folder named assets. This folder is responsible for holding all of the media files, including music, images, and so on. The developer can directly access the folder from the code by writing the getAssets() function within the inherited Activity class. This function returns the AssetManager that can easily be used to access the subfolders and files inside the main assets folder.

The main advantage of the assets folder is that there is no need to keep references for the files placed, which is very handy in the situation where the developer needs to do a test and make a runtime change. Though it does not have any reference, it may introduce errors due to typing mistakes. Another advantage of using assets is that the developer can arrange folders according to his or her will; similarly, the naming conventions for these folders can easily be chosen according to the ease of the developer.

The res folder

The res folder is used to manage an application's resources such as media files, images, user interface layouts, menus, animation, colors, and strings (text) in an Android application; or in other words, you can say that this is the most intelligent way of handling the media files. It consists of many subfolders including drawable, drawable-ldpi, drawable-mdpi, drawable-hdpi, drawable-xhdpi, drawable-xxhdpi, raw, layout, anim, menu, and values.

Drawable is directly related to the images that are used in the Android project. It is an intelligent way of keeping images in the project. As we know that there are various types of devices present in the market that support Android OS. In order to differentiate between these devices, the low resolution images are placed in the ldpi folder for the devices with less resolution. Similarly, the mdpi folder is for the device with medium screen density, hdpi for high density, xhdpi for extra high density, and so on.

Tip

The images placed in these drawable folders should be uniquely named in order to access them with a single reference from the code.

Similarly, for placing music and sound contents, we use the raw folder in order to access them from the code. Any other file apart from the music and sound can also be placed in the raw folder (for example, the JSON file). The same goes with anim, values, menus, and layout folders for placing the animations, values, custom menus, and different types of layouts respectively.

XML components

In Android, a developer needs to use XML in order to make the user interface. Layouts, Menus, Sub Menus, and many other things are defined in the form of different Android tags based on XML. Apart from layouts, you can also store strings, color codes, and many other things in the form of XML files. The component supports the maintenance of the hierarchy of the application and makes it easy to understand for all developers.

Let's take a look at some of the most important XML files that are used as the backbone of any Android application.

The layout folder

Inside the res folder, there is a folder called layout that contains all the layouts of activities. It is to be noted that there are some extensions of this folder, just like the drawable folders. The layout-land and layout-port methods are specifically used for keeping the layout well organized in landscape and portrait mode respectively.

Tip

XML can also be used for making custom drawables that can be used as images in different scenarios. For example, the image of the custom button can be made with XML, which gives a different UI behavior on clicked and non-clicked states.

The preceding screenshot is of Android Studio where you can see an activity_main.xml file that is used to describe the layout of an activity. There are some Android-defined XML tags for RelativeLayout and TextView (read the following information box). Similarly, there are some other tags as well that are available for the developer to include different kinds of widgets in the layout.

Note

RelativeLayout is a layout in which children are placed to the relative positions. This layout is often used by Android mobile developers.

TextView is one of the views that is used to display any kind of text including numbers, strings, and editables.

The menu folder

Android comes with different kind of menus that can be used in order to give quick access to the prominent functionalities that are used within an activity. The different menus available are as follows:

  • Context menus

  • Options menus (with an action bar)

  • Pop-up menus

  • Custom menus

Due to the limited focus of this chapter, we cannot completely elaborate on the functionality and give examples of the different types of menus. However, all types of menus are based on XML files in which Android-defined tags such as <menu>, <item>, and <group> are used to introduce menus in the application. See the following screenshot for reference:

The Android ICS Options menu is on left and the Custom Pop Up menu is on the right

The values folder

The values folder consists of various XML files that can be used by the developer in many scenarios. The most common files for this folder are styles.xml and strings.xml. The style file consists of all the tags that are related to the style of any UI. Similarly, the strings.xml file consists of all the strings that are used in the source code of any Android project. Apart from that, the strings.xml file also contains the <color> tagged hash-coding, which is used to identify many colors inside the source code of an Android application.

AndroidManifest.xml

Unlike the previously mentioned folders, AndroidManifest.xml is a file that contains important information about the Android application. The manifest file consists of various tags such as <application>, <uses-sdk>, <activity>, <intent-filter>, <service>, and many other tags that are enclosed within the main tag of <manifest>.

Just like the tags suggest, this XML file contains all the information about activities, services, SDK versions, and everything that is related to the application. There are various errors that may arise if you don't enter the correct information or miss anything in the AndroidManifest.xml file.

Another major advantage of the AndroidManifest.xml file is that it is the best way to track the structure of any Android application. The total number of activities, services, and receivers can be seen easily by this file. Apart from that, we can change the styles, fonts, SDK constraints, screen-size restrictions, and many other features just by tweaking the AndroidManifest.xml file.

At the time of signing the .apk build, we mention the package name, version name, and version code, which are uniquely identified by the Google Play in order to put the application on the market. The application will then be identified by this package name and further releases are based on changing the version codes and version name described inside the AndroidManifest.xml file.

Referencing components

Another basic component of an Android application is the referencing component. Put simply this component helps XML-based files to interact with the Java code. In Android Studio, the file R.java is placed under the source folder, which is the child of the build folder in the project hierarchy. The R.java file consists of all the references that are used in the XML files for layout, menus, drawables, anim, and so on. This file is then exposed to the activity files to get the references and obtain the objects to perform various functions and parameters.

Mostly, this R.java file is obtained as a part of the project import and used as R.layout.main. In this example, it clearly means that we need to obtain a layout that is a part of the res layout folder and the name of the layout is main. As a result, it will return a resource ID, which is hidden from the developer and directly referenced to the particular layout inside the res folder.

Note

The R.java file is automatically generated while building the project. Hence, it should not be pushed into the repository. Ensure the content of the R.java file is not modified manually. The R.java file that exists in the gen folder of your project is defined by Android at the time of project making or compiling.

Library components

Libraries are pre-built Java files/projects that can be used by anyone to perform certain tasks inside this application. There are various third-party paid/unpaid libraries available that give various functionalities to the developer. Library components are not libraries themselves; rather, they are the project folders in which the libraries are kept.

In an Android project, a folder named libs is present inside the main application folder (Android Studio), which is used as a library component. Any .jar library file can be put under this folder in order to reference it from the code. While using those libraries inside the Java code, you need to import the corresponding package name that is present inside the .jar file in order to use the functions of that particular class.

Similarly, you can use any other Android project as a library by making it a module and importing it inside your project. This functionality was previously called as Library Project in Eclipse, imported by Project Properties | Android | Library Reference.

The Android Studio module importing window

 

Android Activity lifecycle


An Android application consists of one or more activities. These activities are visual representations of an application in transitioning flow while performing the task, taking user inputs, and showing results to the user. Each activity presents the user with a visual representation on the screen for user interaction. Android keeps all the activities in a back stack following the last in, first out rule. Whenever a new activity is started, the current activity is pushed in the back stack. Thus, Android gives focus focuses on the new activity. The activity can take up the whole screen of the device, or it can also take part of the screen, or it can be dragged as well. Whether it is an activity taking the whole area of a screen or a small part of screen, only one activity is focused at a time in Android. When, any existing activity is stopped, it is pushed into the back stack, which in turn results the next top activity being focused.

Note

Android 4.x versions introduced fragments. Fragments can be referred to as sub-activities, which are embedded in an activity to perform different tasks in a single activity at the same time, unlike activities.

Usually, an Android application consists of more than one activity. These activities are loosely bounded with each other. It is a good practice to create each activity for a specific task to be performed. For example, in a simple phone dialing application, there might be one activity to show all contacts, one to show full contact details of any specific contact, one for dialing a number, and so on. In all the applications, there is a main activity that behaves as the starting point of the application. This activity starts when the application is launched. Then this activity starts some other activity, which starts another, and so on. Android manages all the activities in a back stack.

Android Activity back stack

The previous figure shows a simple representation of how back stack works. The area highlighting top activities in a stack represents foreground activity, sometimes called focused activity or running activity. When a new activity is created, it is pushed in the stack, and when any existing activity is destroyed, it is pulled out of the stack. This process of being pushed in the stack and pulled out of the stack is managed by the activity lifecycle in Android. This lifecycle is called Activity lifecycle. The lifecycle manages the activities in the stack and notifies about the changes in the state in the activities through the callback methods of the cycle. An activity receives different types of states such as activity created, activity destroyed, and so on, due to change in the state. A developer overrides these callback methods to perform the necessary steps for respective change of state. For example, when an activity is started, the necessary resources should be loaded, or when an activity is destroyed, those resources should be unloaded for better performance of the app. All these callback methods play a crucial role in managing the Activity lifecycle. It is the developer's choice to override none, some, or all methods.

Fundamental states of an activity

Basically, an activity remains in three states: Resumed, Paused, and Stopped. When an activity is resumed, it is shown on the screen and gets the focus of the user. This activity remains in the foreground section of the back stack. When another activity is started and it becomes visible on the screen, then this activity is paused. This activity still remains on the foreground task, and it is still alive, but it has not gotten any user focus. It is also possible that the new activity partially covers the screen. In that case, the part of the paused activity will be visible on the screen. The activity comes in the Stopped state when it becomes completely invisible from the screen, and is replaced by another activity in the foreground. In this stopped state, the activity is still alive, but it is in the background section of the back stack. The difference between the paused and stopped states is that, in the paused state, the activity is attached to the window manager, but in the stopped state, it is not attached to the window manager.

Note

In an extremely low memory situation, an Android system can kill any paused or stopped activity by asking to finish it, or without asking by killing the process. To avoid this problem, the developer should store all the necessary data in a pause and stop callback, and should retrieve this data in the resume callback.

The callback methods of the Activity lifecycle

There are various callback methods that are called when the state of any activity is changed. Developers perform the necessary tasks and actions in these methods for better performance of the app. To show the Activity lifecycle in action, we are creating a small Android application in this section. Here is the step-by-step approach:

  1. Start Android Studio.

  2. Create an empty project with the details as shown in the following screenshot:

    New Project Dialog in Android Studio

  3. Add the following code in the MainActivity.java file of the project:

    package com.learningandroidintents.callbacksdemo;
    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import android.widget.Toast;
    public class MainActivity extends Activity {
           
     @Override
            public void onCreate (Bundle savedInstanceState){
                super.onCreate(savedInstanceState);
                Toast.makeText( this, "Activity Created!", Toast.LENGTH_SHORT
                ).show();
            }
    @Override
            protected void onStart ()
            {
                super.onStart();
                Toast.makeText(this, "Activity Started!", Toast.LENGTH_SHORT
                ).show();
            }
    
     @Override
            protected void onResume()
            {
                super.onResume();
                Toast.makeText(this, "Activity Resumed!", Toast.LENGTH_SHORT
                ).show();
            }
            
    @Override
            protected void onPause()
            {
                super.onPause();
                Toast.makeText(this, "Activity Paused!", Toast.LENGTH_SHORT
                ).show();
            }
            
    @Override
            protected void onStop()
            {
                super.onStop();
                Toast.makeText(this, "Activity Stopped!", Toast.LENGTH_SHORT
                ).show();
            }
    
            
    
    @Override
            protected void onDestroy()
            {
                super.onDestroy();
                Toast.makeText(this, "Activity Destroyed!", Toast.LENGTH_SHORT
                ).show();
            }
        }
  4. Run the project in the emulator, and you will see toasts being printed on screen in the following order:

    • Activity Created

    • Activity Started

    • Activity Resumed

    • Activity Paused

    • Activity Stopped

    • Activity Destroyed

Let us see the working of the previously mentioned code.

When you run the project, the emulator will display all the toasts in the previously given order on the screen. At the start of project, an activity is created, and then the activity is started. After starting the activity, it is displayed on the screen and emulator prints Resumed. Now, we go back by pressing the back key, and the Android system prepares to finish the activity. So, the activity is first paused, then it is stopped, and finally it is destroyed. All these callbacks together are called the Activity lifecycle. Activity lifecycle starts from the onCreate() method and it stops at the onStop() method. The activity is visible from the onStart() method to the onStop() method, and the activity remains in foreground from the onResume() method to the onPause() method. The following figure shows this cycle distribution:

The activity lifecycle flow

Until now, we have discussed the lifecycle callback methods used, their states, and their purpose. Now, we will look into the callback method's flow. In Android, when one activity is started, the already opened activity is stopped, and this change of activity happens in a flow. The following figure shows the visual flowchart of the Activity lifecycle:

Callback methods are shown with rectangles. The very first step in the Activity lifecycle is to create an activity. Android creates an activity, if no instance of that activity is running in the same task. The noHistory tag does not allow multiple activities; rather it will determine whether an activity will have historical trace or not (refer to http://developer.android.com/guide/topics/manifest/activity-element.html#nohist), where you can determine multiple instances by the android:launchmode flag tag. Making this tag's value true means only one instance of the activity will be created in the stack, and whenever an activity intent is called, the same instance is pushed on top of the stack to show the activity on screen.

After the onCreate() method, the onStart() method is called. This method is responsible for the initial settings, but it is best practice configure these in the onResume() method, which is called after the onStart() method. Remember, the foreground phase is started from the onResume() method. Say a user gets a call on his or her phone, then this activity will be paused through the onPause() method. So, all the steps involved in storing the necessary data when the activity is paused should be done here. This method can be very beneficial in critical memory situations because in these situations, Android can stop the paused activities, which in turn can show unexpected behavior in the app. If the activity is killed due to a critical memory situation, the onCreate() method is called instead of the onResume() method, resulting in the creation of a new instance of the activity.

But, if everything goes right, then the activity returns to its same state through the onResume() method. In this method, the user can do all the work of reloading the stored data in the onPause() method, and can get the activity back to life. On turning off the activity after onResume() is launched the onStop() method is called. This triggers either the onRestart() method, or the onDestroy() method depending on user action. In a nutshell, the developer can control the Activity lifecycle using callback methods. It is a good practice to use the onPause() and onResume() methods for data management, whether the activity remains foreground or not, and onCreate() and onDestroy() should be used for only initial data management and cleaning up the resources respectively.

Note

All callback methods except the onCreate() method take no parameter or argument. In case of a critical memory situation, if an activity is destroyed, then that instance state is passed in the onCreate() method at the time of creation of that activity.

It is not necessary to override all the methods. The user can override any number of methods as there is no such restriction on it. The user should set a view in the onCreate() method. If you don't set any view for the content, a blank screen will show up. In each callback, first of all, the same callback method of the superclass should be called before doing anything. This super callback method operates the Activity lifecycle through standard flow developed by Android systems.

 

Summary


In this chapter, we explored the key concepts of Android. We discussed about Android, its versions that are named after sugar treats, covered a brief history of Android, and how its founders released Android with Google. We also discussed Google Play, an official store for Android apps; Android Studio, an official IDE from Google, and its features and limitations. Then we moved our discussion to a development perspective, and we discussed the building blocks for any Android application. We also discussed the Activity lifecycle, which plays a very important role in any Android application, its flow, its callback methods, and and looked at an example of it.

In the next chapter, we will discuss the intents, role played by the intents in Android, a technical overview, structure, and its uses in Android.

About the Authors

  • Muhammad Usama bin Aftab

    Muhammad Usama bin Aftab is a software engineer at one of the leading solar lighting manufacturers in North America. At Carmanah Technologies, he works closely with the product development and management teams to develop software for embryonic technologies such as Bluetooth Low Energy. He also focuses on full-stack development using Angular 2 and Java. His main areas of interest range from mobile application development to information security. Mr. Aftab is an alumnus of the University of Victoria, Canada, where he received his master's degree in applied science in electrical and computer engineering. Mr. Aftab has experience in Android, iOS, and cross-platform gaming technologies (such as Unity 3D), which led him to coauthor Learning Android Intents for Packt in 2014.

    Browse publications by this author
  • Wajahat Karim

    Wajahat Karim is a seasoned mobile app and game developer with extensive experience in diversified technologies, as well as more than 7 years of software development experience.

    Wajahat received his information and communication systems engineering degree from the NUST School of Electrical Engineering and Computer Sciences (SEECS), Islamabad, Pakistan. He has been working on games since he was 14 years old and is skilled in many platforms, including Android SDK, AndEngine, Adobe Flash, Adobe AIR, Game Maker, and Unity3D.

    He is skilled, not only in programming and coding, but also in computer graphic designing tools such as Adobe Photoshop, Adobe Illustrator, Adobe Flash, and Autodesk Maya. Recently, he also worked with the government of Oman in Muscat, to create a real-time election monitoring app for Android and iOS for their Shura Elections, 2015. He has run multiple startups from time to time and has also worked in a virtual reality and augmented reality startup.

    Currently, besides being a full-time development manager at a multinational company, he is working with a startup that allows Android developers to boost their app growth and reward their users through in-app perks.

    Wajahat has deep passion in game development, entrepreneurship, and writing. He has previously coauthored the book Learning Android Intents by Packt Publishing.

    You can reach Wajahat on his personal website.

    Browse publications by this author

Latest Reviews

(1 reviews total)
Book is good i enjoyed reading it.