Main Building Blocks in Android
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.
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.
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
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.
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.
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.
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.
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.nt
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.
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.
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 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.
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
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
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.
Figure 4.5. 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.
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.