9781449390501
Main_Building_Blocks.html

Chapter 4. Main Building Blocks

If you're new to the Android mobile operating system, Learning Android is the perfect way to master the fundamentals. This gentle introduction shows you how to use Android's basic building blocks to develop user interfaces, store data, and more. Buy the print book or ebook.

In this chapter, you will learn about the big blocks in Android. We’ll give you a high-level overview of what Activities are, how Intents work, why Services are cool, how to use Broadcast Receivers and Content Providers to make your app scale, and much more.

By the end of this chapter, you will understand the main Android components for building applications. You should conceptually know when you’d use what component. You will also see how these components relate to a real world application.

Main Building Blocks

Main building blocks are components that you use as an application developer to build Android apps. They are the conceptual items that you put together to create a bigger whole. When you start thinking about your application, it is good to approach it top down. You design your application in terms of screens, features, and interactions between them. You start with conceptual drawing, something that you can represent in terms of "lines and circles". This approach to application development helps you see the big picture - how the components fit together and it all makes sense.

A Real World Example

Let’s say that we want to build a Twitter app. We know that the user should be able to post status updates. We also know the user should be able to see what her friends are up to. Those are basic features. Beyond that, the user should also be able to set her username and password in order to login to her Twitter account. So, now we know we should have these three screens.

Next, we would like my app to work fast regardless of network connection, or lack of. To achieve that, the app has to pull the data from Twitter when it’s online, and cache it locally. That will require a service that runs in the background as well as a database.

We also know that we’d like this background service to be started when the device is initially turned on, so by the user first uses the app, there’s already up-to-date information on her friends.

So, these are some straightforward requirements. Android building blocks make it easy to break them down into conceptual units so that you can work on them independently, and can also easily put them together into a complete package.

Activities

An activity is usually a single screen that the user sees on the device at one time. An application typically has multiple activities and the user flips back and forth among them. As such, activities are the most visible part of your application.

I usually use a website as an analogy for activities. Just like a website consists of multiple pages, so does an Android application consists of multiple activities. Just like a website has a "home page", an Android app has a "main" activity. It is usually the one that is shown first when you launch the application. And just like a website has to provide some sort of navigation among various pages, an Android app should do the same.

On the web, you can jump from a page on one website to a page on another. Similarly, in Android, you could be looking at an activity of one application, but shortly after you could start another activity in a completely separate application. For example, if you are in your Contacts app, and you choose to text a friend, you’d be launching the activity to compose a text message in the Messaging application.

Activity Lifecycle

Launching an activity may be quite expensive. It may involve creating a new linux process, allocating memory for all the UI objects, inflating all the objects from XML layouts, and setting the whole screen up. Since we’re doing a lot of work to launch an activity, it’s be a waste to just toss it out once user leaves that screen. To avoid this waste, activity lifecycle is managed via Activity Manager.

Activity Manager is responsible for creating, destroying, and overall managing activities. For example, when the user starts an application for the first time, the activity manager will create its activity and put it onto the screen. Later, when the user switches screens, the activity manger will move that previous activity to a holding place. This way, if the user wants to go back to an older activity, it can be started more quickly. Older activities that user hasn’t used in a while will be destroyed in order to free more space for the currently active one. This mechanism is designed to help improve the speed of user interface and thus improve the overall user experience.

Figure 4.1. Activity Lifecycle

Activity Lifecycle

Programming for Android is conceptually different than programming for some other environments. In Android, you find yourself more responding to certain changes in the state of your application rather than driving that change yourself. It is a managed, container-based environment similar to programming for Java applets or servlets. So, when it comes to activity lifecycle, you don’t get to say what state the activity is in but you have plenty of opportunity to say what happens on transitions from state to state.

Starting State

When an activity doesn’t exist in memory, it is in Starting State. While it’s starting up, the activity will go through a whole set of callback methods that you as a developer have an opportunity to fill out. Eventually, the activity will be in Running State.

Keep in mind that this transition from Starting State to Running State is one of the most expensive operations in terms of computing time needed. The computing time directly effects the battery life of the device as well. This is the exact reason why we don’t automatically destroy activities that are no longer shown. User may want to come back to them, so we keep them around for awhile.

Running State

Activity in a Running State is the one that is currently on the screen interacting with the user. We also say this activity is in focus, meaning that all user interactions, such as typing, touching screen, clicking buttons, are handled by this one activity. As such, there is only one running activity at any one time.

The running activity is the one that has all the priorities in terms of getting memory and resources needed to run as fast as possible. This is because Android wants to make sure the running activity is zippy and responsive to user.

Paused State

When an activity is not in focus (i.e. not interacting with the user) but still visible on the screen, we say it’s in Paused State. This is not a very typical scenario since the screen is usually small and an activity is either taking the whole screen or not at all. We often see this case with dialog boxes that come up in front an activity causing it to become Paused. Paused State is a state that all activities go through it en route to being stopped.

Paused activities still have high priority in terms of getting memory and other resources. This is because they are visible and cannot be removed from the screen without making it look very strange to the user.

Stopped State

When an activity is not visible, but still in memory, we say it’s in Stopped State. Stopped activity could be brought back to front to become a Running activity again. Or, it could be destroyed and removed from memory.

System keeps activities around in Stopped State because it is likely that the user will still want to get back to those activities some time soon. And restarting a stopped activity is far cheaper than starting an activity from scratch. That is because we already have all the objects loaded in memory and just simply have to bring it all up to foreground.

Stopped activities can also, an any point, be removed from memory.

Destroyed State

A destroyed activity is no longer in memory. The Activity Manager decided that this activity is no longer needed, and as such has removed it. Before the activity is destroyed, you, the developer, have an opportunity to perform certain actions, such as save any unsaved information. However, there’s no guarantee that your activity will be Stopped prior to being Destroyed. It is possible that a Paused activity gets destroyed as well. For that reason, it is better to do important work, such as saving unsaved data, en route to being Paused rather than Destroyed.

Note

The fact that an activity is in Running State doesn’t mean it’s doing much. It could be just sitting there and waiting for user input. Similarly, an activity in Stopped State is not necessarily doing nothing. The state names mostly refer to how active the activity is with respect to user input. In other words, weather an activity is in visible, in focus, or not visible at all.

Intents

Figure 4.2. Intents

Intents

Intents are messages that are sent among major building blocks. They trigger an activity to start up, a service to start or stop, or are simply broadcasts. Intents are asynchronous, meaning the code that is sending them doesn’t have to wait for them to be completed.

An intent could be explicit or implicit. In an explicit intent the sender clearly spells out which specific component should be on the receiving end. In an implicit intent, the sender specifies the type of receiver. For example, your activity could send an intent saying it simply wants someone to open up a web page. In that case, any application that is capable of opening a web page could "compete" to complete this action.

When you have competing applications, the system will ask you which one you’d like to use to complete a given action. You can also set an app as the default one. This mechanism works very similarly to your desktop environment, when you downloaded Firefox or Chrome to replace your default Internet Explorer or Safari web browsers.

What this type of messaging allows for is to allow the user to replace any app on the system with a custom one. For example, you may want to download a different SMS application, or another browser to replace your existing ones.

Services

Services run in the background and don’t have any user interface components. They can perform the same actions as Activities without any user interface. Services are useful for actions that we want to make sure performs for a while, regardless of what is on the screen. For example, you may want to have your music player play music even as you are flipping between other applications.

Note

Don’t confuse Android Services that are part of an Android app with native linux services, servers or daemons that a much lower level component of the operating system.

Figure 4.3. Service Lifecycle

Service Lifecycle

Services have a much simpler lifecycle than activities. You start a service, or stop it. Also, the service lifecycle is more or less controlled by the developer, and not so much by the system. So, we as developers have to be mindful to run our services so that they don’t unnecessarily consume shared resources, such as CPU and battery.

Note

The fact that a service runs in the background doesn’t mean it runs on a separate thread. If a service is doing some processing that takes a while to complete (such as perform network calls), you would typically run it on a separate thread. Otherwise, your user interface will run noticeably slower. In other words, Services and Activities run on the same main application thread, often called UI thread.

Content Providers

Figure 4.4. Content Provider

Content Provider

Content Providers are interfaces for sharing data between applications. Android by default runs each application in its own sandbox so that all data that belongs to an application is totally isolated from other applications on the system. While small amounts of data can be passed between applications via Intents, Content Providers are much better suited for sharing persistent data between possibly large datasets. As such, Content Provider API nicely adheres to CRUD principle.

Android system uses this mechanism all the time. For example, Contacts Provider is a content provider that exposes all users contacts data to various applications. Settings Provider exposes system settings to various applications including the built-in Settings application. Media Store is responsible for storing and sharing all various media, such as photos, and music across various applications.

This separation of data storage and the actual user interface application offers greater flexibility to mash up various parts of the system. For example, a user could install an alternative Address Book application that uses the same data as the default Contacts app. Or, install widgets on the Home Screen that allow for easy changes in the System Settings, such as turning on or off the Wifi, Bluetooth or GPS features. Many phone manufactures take advantage of Content Providers to add their own applications on top of standard Android to improve overall user experience, such as HTC Sense.

Content Providers are a relatively simple interface with the standard insert(), update(), delete() and query() methods. These methods look a lot like standard database methods, so it is relatively easy to implement a content provider as a proxy to the database. Having said that, you are much more likely to use content providers than write your own.

Broadcast Receivers

Figure 4.5. Broadcast Receiver

Broadcast Receiver

Broadcast Receivers is an Android implementation of system-wide publish/subscribe mechanism (more precisely, this is an Observer pattern). The receiver is simply a dormant code that gets activated once an event it is subscribed to happens.

The system itself broadcasts events all the time. For example, when an SMS arrives, or call comes in, or battery runs low, or system gets booted, all those events are broadcasted and any number of receivers could be triggered by them.

In our Twitter app example, we want to start the update service once the system starts up. To do that, we can subscribe to the broadcast that tells us the system has completed booting up.

You can also send your own broadcasts from one part of your application to another, or a totally different application.

Broadcast receivers themselves do not have any visual representation nor are they actively running in memory. But when triggered, they get to execute some code, such as start an activity, a service, or something else.

Application Context

So far you have seen Activities, Services, Content Providers and Broadcast Receiver. Together, they make up an application. Another way of saying that is that they live inside the same Application Context.

Application Context refers to the application environment and process within all its components are running. It allows to sharing of the data and resources between various Building Blocks.

Application Context gets created whenever the first component of this application is started up, regardless whether that component is an activity, service, or something else. Application context lives as long as your application is alive. As such, it is independent of the activities life cycle. You can easily obtain reference to the context by calling Context.getApplicationContext() or Activity.getApplication(). Keep in mind that activities and services are already subclasses of context, and as such inherit all its methods.

Summary

In this chapter, you have learned about some of the most important Android application components. We put together these components to create various applications, from a simple Hello World to much more complex creations.

In the next chapter, we’ll outline Yamba application as an example of how all these bits and pieces come together to form a working Android app.

Site last updated on: April 8, 2011 at 12:51:47 PM PDT
Cover for Learning Android

View 1 comment

  1. schrickl – Posted Sept. 2, 2010

    Do you mean to say "the big building blocks in Android"?

Add a comment

View 1 comment

  1. schrickl – Posted Sept. 2, 2010

    "Main building blocks are components that you use as an application developer to build Android apps."

Add a comment

View 2 comments

  1. schrickl – Posted Sept. 2, 2010

    Maybe replace "she" with "he/she", "her" with "his/her"

  2. fmaker – Posted Sept. 18, 2010

    I'd like to see a diagram here either with a simple mockup or some UML.

Add a comment

View 1 comment

  1. groshev – Posted Aug. 1, 2011

    "...we would like our app..."

    Edited on August 1, 2011, 4:53 a.m. PDT

Add a comment

View 1 comment

  1. schrickl – Posted Sept. 2, 2010

    "...the device is initially turned on, so 'when' the user first uses the app,..."

Add a comment

View 2 comments

  1. schrickl – Posted Sept. 2, 2010

    froward should be forward

  2. herve – Posted Sept. 11, 2010

    "straightforward", in one word.

Add a comment

View 2 comments

  1. schrickl – Posted Sept. 2, 2010

    "the" user

  2. fmaker – Posted Sept. 18, 2010

    Also might not be inside your application for common actions such as choosing pictures in the gallary, sending SMS messages, etc.

Add a comment

View 3 comments

  1. schrickl – Posted Sept. 2, 2010

    "...among various pages..."

  2. fmaker – Posted Sept. 18, 2010

    Brilliant!

  3. Marilyn Escue – Posted Nov. 26, 2010

    Yes, this is a very good analogy to use.

Add a comment

View 3 comments

  1. herve – Posted Sept. 1, 2010

    A new process is not necessarily created when an activity is launched (see android:process attribute for application, activity, etc). Maybe using "may be quite expensive" would be better (same with "It may be" and "it may involve").

  2. fmaker – Posted Sept. 18, 2010

    Couple problems here: 1) Zygote process is always waiting for implement your new application so there is not new process created. However, when the zygote is "born" another one must be created again to wait for the new application. 2) The activity does not cause this to happen, it's the starting of something inside the apk. Which is often an Activity, but could also be a service for ex.

  3. Abhishek Adappa – Posted May 31, 2011

    "...it’s be a waste to ..." -> "...it would be a waste to ..."

Add a comment

View 4 comments

  1. schrickl – Posted Sept. 2, 2010

    "...when the user wants to start an application for the first time, the activity manager will create its activity and put it onto the screen."

    "...it can be started more quickly."

  2. herve – Posted Sept. 11, 2010

    "when the user starts an application for the first time"

    instead of

    "when the user wants to start an application for the first time"?

  3. Clemens Hladek – Posted Jan. 30, 2011

    ... will create its MAIN activity or: will create AN activity...

  4. Enrique Matias Sanchez – Posted March 22, 2011

    the activity manger will move that previous activity

    manager

Add a comment

View 3 comments

  1. fmaker – Posted Sept. 19, 2010

    I'd like to see an example here of responding as opposed to driving changes yourself. To make it very clear to the reader. This is an important concept.

  2. fmaker – Posted Sept. 19, 2010

    This diagram is too simple compared to the official one. For instance, the significance of onResume is pretty lost here.

  3. sonicpp – Posted Sept. 29, 2011

    Instead of "you find yourself more responding to certain changes" you should say "you find yourself responding more to certain changes".

Add a comment

View 2 comments

  1. schrickl – Posted Sept. 2, 2010

    "...that you as a developer..."

  2. Marilyn Escue – Posted Nov. 26, 2010

    should just be "it is in the Start state. It's awkward to see it as "in the section called x state". This happens throughout the rest of this chapter as well.

Add a comment

View 3 comments

  1. fmaker – Posted Sept. 19, 2010

    Very good, you should also mention expensive in computing time also effects battery life for example.

  2. stevemeuse – Posted April 5, 2011

    "effects" -> "affects"

  3. groshev – Posted Aug. 1, 2011

    "...we keep around them for a while..."

Add a comment

View 2 comments

  1. schrickl – Posted Sept. 2, 2010

    Remove "A" from the beginning of the paragraph.

    "As such, there is only one running activity at any one time."

  2. herve – Posted Sept. 11, 2010

    "The running activity is the one..."

Add a comment

View 2 comments

  1. herve – Posted Sept. 11, 2010

    "This is because Android wants to make sure the running activity is zippy and responsive to user."

  2. David Breece – Posted Feb. 4, 2011

    "responsive to the user"

Add a comment

View 5 comments

  1. schrickl – Posted Sept. 2, 2010

    "But, 'none' the less,..."

  2. fmaker – Posted Sept. 19, 2010

    Mention that this is often the case with dialog boxes.

  3. Magnus Flansbjer – Posted March 12, 2011

    Revise the last sentence. Suggestion: "All activities go through the Paused State en route to being stopped."

  4. Abhishek Adappa – Posted May 31, 2011

    "that come up in front an activity causing" -> "that come up in front 'of' an activity causing"

  5. Manikandan BAKTHAVATCHALAM – Posted Jan. 21, 2012

    Can give 1 more example for an activity on pause

Add a comment

View 1 comment

  1. Johnathan Moore – Posted Jan. 27, 2011

    "The stopped activity could be brought back ..." or "A stopped activity could be ..." or "An activity that has been stopped could be ..."

Add a comment

View 2 comments

  1. Nigel Gilbert – Posted Feb. 4, 2011

    Perhaps start this paragraph:

    "The system keeps..."

  2. Abhishek Adappa – Posted May 31, 2011

    Maybe reword this

    "just simply have to bring it all up to foreground." -> "we simply have to bring it all up to foreground.

Add a comment

View 1 comment

  1. Magnus Flansbjer – Posted March 12, 2011

    at any point

Add a comment

View 4 comments

  1. fmaker – Posted Sept. 19, 2010

    Good place to mention that Destroyed is the not the same as Java's finalizing.

  2. fmaker – Posted Sept. 19, 2010

    This note shouldn't use sensor updates, because that is something that likely should not be done while the activity is stopped!!!

  3. Ravishankar Rajagopalan – Posted Dec. 8, 2010

    I feel this may do with a little bit of change. The activity can move from the Paused state to the Destroyed state. In that case the onDestroy method is not called and the user ha no opportunity to perform any action. Important activities like state saving need to be done on or before onPause() is called, as recommended in the Android documentation.

  4. Johnathan Moore – Posted Jan. 27, 2011

    In the note: "whether an activity", not "weather an activity"

Add a comment

View 1 comment

  1. fmaker – Posted Sept. 19, 2010

    I would add that analogy you use in class, about the "Default web browser". I really like that example.

Add a comment

View 3 comments

  1. fmaker – Posted Sept. 19, 2010

    Oh you did mention that browser example, it would be better to move it up to the beginning so they can start with that understanding and then confirm it as they read. Rather than making is so clear at the end.

  2. Nigel Gilbert – Posted Feb. 4, 2011

    It might be better to say that "the system will ask the user which one they'd like to use" to continue the distinction between "you" (the developer) and the device user.

  3. Manikandan BAKTHAVATCHALAM – Posted Jan. 21, 2012

    A good example for "competing applications" would be when you want to save a new contact and the contacts application asks you if you want to save it to the SD card, phone or google account associated with your android phone.

Add a comment

View 3 comments

  1. herve – Posted Sept. 9, 2010

    While services run in the background, they are not separate processes/threads (as in Linux terminology), so maybe it should say "Services run in the background and don't have any user interface components" so readers are not confused.

    The following line in the Android documentation is quite important: "Like activities and the other components, services run in the main thread of the application process. So that they won't block other components or the user interface, they often spawn another thread for time-consuming tasks (like music playback)."

  2. fmaker – Posted Sept. 19, 2010

    It would be good to emphasize here that services not daemons or constantly running servers. In fact there are different apis availiable so that your service won't be available all the time.

    Also, I wouldn't use twitter as an example because new apps should be using the SyncManager now instead of their own service. Music is a good example though.

  3. fmaker – Posted Sept. 19, 2010

    I would simply with "Services can perform that same things as Activities without any user interface" .... and also constant things like music and repetitive things as well. (Make whatever sense you can of that ;-)

Add a comment

View 4 comments

  1. fmaker – Posted Sept. 19, 2010

    I disagree, because many bad applications out have services that are running all the time. Whereas activities are often mostly idle, waiting for user input.

  2. Ravishankar Rajagopalan – Posted Dec. 8, 2010

    Whether a service is easy on resources or not really depends on what they are doing.

  3. Ravishankar Rajagopalan – Posted Dec. 8, 2010

    Typo - ..depends on what it is doing.

  4. Enrique Matias Sanchez – Posted March 23, 2011

    servers or daemons that a much lower level component

    servers or daemons that are a much lower level component

Add a comment

View 3 comments

  1. fmaker – Posted Sept. 19, 2010

    These are useful for data that is persistant and conforms to the CRUD principle

  2. fmaker – Posted Sept. 19, 2010

    Could mention that intents can be used for a small amount of one-shot data, where as content providers are more for recurring requests with possibly large and changing data.

  3. andyo – Posted Sept. 23, 2010

    I agree with Frank Maker's comments, and suggest that you take a step back to explain why data needs to be provided by external data providers on a mobile platform. The obvious example is the Contacts database, which should be provided to multiple applications and should not belong to a single application. The idea of one application preserving data and serving it up to others is the motivation for a Content Provider.

Add a comment

View 1 comment

  1. fmaker – Posted Sept. 19, 2010

    mention that you can access many of these content providers such as the address book.

Add a comment

View 1 comment

  1. fmaker – Posted Sept. 19, 2010

    good point about using not writing mostly.

Add a comment

View 2 comments

  1. fmaker – Posted Sept. 19, 2010

    Mention this is an observer pattern.

  2. fmaker – Posted Sept. 19, 2010

    Also, I like to use the analogy of a radio that "tunes into" an even broadcast. Use if you like.

Add a comment

View 1 comment

  1. fmaker – Posted Sept. 19, 2010

    mention you can see many of these events by using logcat.

Add a comment

View 3 comments

  1. schrickl – Posted Sept. 2, 2010

    "Nor are they actively running in memory."

  2. fmaker – Posted Sept. 19, 2010

    Mention sticky broadcasts too.

  3. Abhishek Adappa – Posted May 31, 2011

    Applies to the text below.

    "Application Context refers to the application environment and process within all its components are running. It allows to sharing of the data and resources between various Building Blocks."

    ->

    "Application Context refers to the application environment and process within 'which' all its components are running. It allows 'the' sharing of data and resources between various Building Blocks."

Add a comment