Understanding Hello World
10:32 AM // 0 comments // Sajib Barua // Category: Android Applications //previous Creating Your First Android Activity
With that confirmed, let’s take a step back and have a real look at your first Android application.
Activity is the base class for the visual, interactive components of your application; it is roughly equivalent to a Form in traditional desktop development. The following snippet shows the skeleton code for an Activity-based class; note that it extends Activity, overriding the onCreate method.
package com.paad.helloworld;
import android.app.Activity;
import android.os.Bundle;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
}
}
What’s missing from this template is the layout of the visual interface. In Android, visual components are called Views, which are similar to controls in traditional desktop development.
In the Hello World template created by the wizard, the onCreate method is overridden to call setContentView, which lays out the user interface by inflating a layout resource, as highlighted below:
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
}
The resources for an Android project are stored in the res folder of your project hierarchy, which includes drawable, layout, and values subfolders. The ADT plug-in interprets these XML resources to provide design time access to them through the R variable.
The following code snippet shows the UI layout defined in the main.xml fi le created by the Android project template:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Hello World, HelloWorld”
/>
</LinearLayout>
Defining your UI in XML and inflating it is the preferred way of implementing your user interfaces, as it neatly decouples your application logic from your UI design.
To get access to your UI elements in code, you add identifier attributes to them in the XML definition. You can then use the findViewById method to return a reference to each named item. The following XML snippet shows an ID attribute added to the TextView widget in the Hello World template:
<TextView
android:id=”@+id/myTextView”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Hello World, HelloWorld”
/>
And the following snippet shows how to get access to it in code:
TextView myTextView = (TextView)findViewById(R.id.myTextView);
Alternatively (although it’s not considered good practice), if you need to, you can create your layout directly in code as shown below:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout.LayoutParams lp;
lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
LinearLayout.LayoutParams textViewLP;
textViewLP = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
TextView myTextView = new TextView(this);
myTextView.setText(“Hello World, HelloWorld”);
ll.addView(myTextView, textViewLP);
this.addContentView(ll, lp);
}
All the properties available in code can be set with attributes in the XML layout. As well as allowing easier substitution of layout designs and individual UI elements, keeping the visual design decoupled from the application code helps keep the code more concise.
The Android web site (http://code.google.com/android/documentation.html) includes several excellent step-by-step guides that demonstrate many of the features and good practices you will be using as an Android developer. They’re easy to follow and give a good idea of how Android applications fi t together.
Types of Android Applications
Most of the applications you create in Android will fall into one of the following categories:
-
Foreground Activity An application that’s only useful when it’s in the foreground and is effectively suspended when it’s not visible. Games and map mashups are common examples.
-
Background Service An application with limited interaction that, apart from when being configured, spends most of its lifetime hidden. Examples of this include call screening applications or SMS auto-responders.
-
Intermittent Activity Expects some interactivity but does most of its work in the background. Often these applications will be set up and then run silently, notifying users when appropriate. A common example would be a media player.
Complex applications are difficult to pigeonhole into a single category and include elements of all three. When creating your application, you need to consider how it’s likely to be used and then design it accordingly. Let’s look more closely at some of the design considerations for each application type described above.
Foreground Activities
When creating foreground applications, you need to consider the Activity life cycle carefully so that the Activity switches seamlessly between the foreground and the background.
Applications have no control over their life cycles, and a backgrounded application, with no Services, is a prime candidate for cleanup by Android’s resource management. This means that you need to save the state of the application when the Activity becomes invisible, and present the exact same state when it returns to the foreground.
It’s also particularly important for foreground Activities to present a slick and intuitive user experience.
Background Services
These applications run silently in the background with very little user input. They often listen for messages or actions caused by the hardware, system, or other applications, rather than rely on user interaction.
It’s possible to create completely invisible services, but in practice, it’s better form to provide at least some sort of user control. At a minimum, you should let users confirm that the service is running and let them configure, pause, or terminate it as needed.
Intermittent Activities
Often you’ll want to create an application that reacts to user input but is still useful when it’s not the active foreground Activity. These applications are generally a union of a visible controller Activity with an invisible background Service.
These applications need to be aware of their state when interacting with the user. This might mean updating the Activity UI when it’s visible and sending notifications to keep the user updated when it’s in the background.
Developing for Mobile Devices
Android does a lot to simplify mobile-device software development, but it’s still important to understand the reasons behind the conventions. There are several factors to account for when writing software for mobile and embedded devices, and when developing for Android, in particular.
Hardware-Imposed Design Considerations
Small and portable, mobile devices offer exciting opportunities for software development. Their limited screen size and reduced memory, storage, and processor power are far less exciting, and instead present some unique challenges.
Compared to desktop or notebook computers, mobile devices have relatively:
-
Low processing power
-
Limited RAM
-
Limited permanent storage capacity
-
Small screens with low resolution
-
Higher costs associated with data transfer
-
Slower data transfer rates with higher latency
-
Less reliable data connections
-
Limited battery life
It’s important to keep these restrictions in mind when creating new applications.
Be Efficient
Manufacturers of embedded devices, particularly mobile devices, value small size and long battery life over potential improvements in processor speed. For developers, that means losing the head start traditionally afforded thanks to Moore’s law. The yearly performance improvements you’ll see in desktop and server hardware usually translate into smaller, more power-efficient mobiles without much improvement in processor power.
In practice, this means that you always need to optimize your code so that it runs quickly and responsively, assuming that hardware improvements over the lifetime of your software are unlikely to do you any favors.
Since code efficiency is a big topic in software engineering, I’m not going to try and capture it here. This chapter covers some Android-specific efficiency tips below, but for now, just note that efficiency is particularly important for resource-constrained environments like mobile devices.
Expect Limited Capacity
Advances in flash memory and solid-state disks have led to a dramatic increase in mobile-device storage capacities (although people’s MP3 collections tend to expand to fill the available space). In practice, most devices still offer relatively limited storage space for your applications. While the compiled size of your application is a consideration, more important is ensuring that your application is polite in its use of system resources.
You should carefully consider how you store your application data. To make life easier, you can use the Android databases and Content Providers to persist, reuse, and share large quantities of data. For smaller data storage, such as preferences or state settings, Android provides an optimized framework.
Of course, these mechanisms won’t stop you from writing directly to the file system when you want or need to, but in those circumstances, always consider how you’re structuring these files, and ensure that yours is an efficient solution.
Part of being polite is cleaning up after yourself. Techniques like caching are useful for limiting repetitive network lookups, but don’t leave fi les on the file system or records in a database when they’re no longer needed.
Design for Small Screens
The small size and portability of mobiles are a challenge for creating good interfaces, particularly when users are demanding an increasingly striking and information-rich graphical user experience.
Write your applications knowing that users will often only glance at the (small) screen. Make your applications intuitive and easy to use by reducing the number of controls and putting the most important information front and center.
Graphical controls are an excellent way to convey dense information in an easy-to-understand way. Rather than a screen full of text with lots of buttons and text entry boxes, use colors, shapes, and graphics to display information.
If you’re planning to include touch-screen support (and if you’re not, you should be), you’ll need to consider how touch input is going to affect your interface design. The time of the stylus has passed; now it’s all about finger input, so make sure your Views are big enough to support interaction using a finger on the screen.
Of course, mobile-phone resolutions and screen sizes are increasing, so it’s smart to design for small screens, but also make sure your UIs scale.
Expect Low Speeds, High Latency
The mobile Web unfortunately isn’t as fast, reliable, or readily available as we’d often like, so when you’re developing your Internet-based applications, it’s best to assume that the network connection will be slow, intermittent, and expensive. With unlimited 3G data plans and city-wide Wi-Fi, this is changing, but designing for the worst case ensures that you always deliver a high-standard user experience.
This also means making sure that your applications can handle losing (or not finding) a data connection.
The Android Emulator lets you control the speed and latency of your network connection when setting up an Eclipse launch configuration. Figure 2-7 shows the emulator’s network connection speed and latency set up to simulate a distinctly suboptimal EDGE connection.
Experiment to ensure responsiveness no matter what the speed, latency, and availability of network access. You might find that in some circumstances, it’s better to limit the functionality of your application or reduce network lookups to cached bursts, based on the network connection(s) available.
At What Cost?
If you’re a mobile owner, you know all too well that some of the more powerful features on your mobile can literally come at a price. Services like SMS, GPS, and data transfer often incur an additional tariff from your service provider.
It’s obvious why it’s important that any costs associated with functionality in your applications are minimized, and that users are aware when an action they perform might result in them being charged.
It’s a good approach to assume that there’s a cost associated with any action involving an interaction with the outside world. Minimize interaction costs by the following:
-
Transferring as little data as possible
-
Caching data and GPS results to eliminate redundant or repetitive lookups
-
Stopping all data transfers and GPS updates when your activity is not visible in the foreground if they’re only being used to update the UI
-
Keeping the refresh/update rates for data transfers (and location lookups) as low as practicable
-
Scheduling big updates or transfers at “off peak” times using alarms
Often the best solution is to use a lower-quality option that comes at a lower cost.
When using the location-based services, you can select a location provider based on whether there is an associated cost. Within your location-based applications, consider giving users the choice of lower cost or greater accuracy.
In some circumstances, costs are hard to define, or they’re different for different users. Charges for services vary between service providers and user plans. While some people will have free unlimited data transfers, others will have free SMS.
Rather than enforcing a particular technique based on which seems cheaper, consider letting your users choose. For example, when downloading data from the Internet, you could ask users if they want to use any network available or limit their transfers to only when they’re connected via Wi-Fi.
Considering the Users’ Environment
You can’t assume that your users will think of your application as the most important feature of their phones.
Generally, a mobile is first and foremost a phone, secondly an SMS and e-mail communicator, thirdly a camera, and fourthly an MP3 player. The applications you write will most likely be in a fifth category of “useful mobile tools.”
That’s not a bad thing — it’s in good company with others including Google Maps and the web browser. That said, each user’s usage model will be different; some people will never use their mobiles to listen to music, and some phones don’t include a camera, but the multitasking principle inherent in a device as ubiquitous as it is indispensable is an important consideration for usability design.
It’s also important to consider when and how your users will use your applications. People use their mobiles all the time — on the train, walking down the street, or even while driving their cars. You can’t make people use their phones appropriately, but you can make sure that your applications don’t distract them any more than necessary.
What does this mean in terms of software design? Make sure that your application:
-
Is well behaved Start by ensuring that your Activities suspend when they’re not in the foreground. Android triggers event handlers when your Activity is suspended or resumed so you can pause UI updates and network lookups when your application isn’t visible — there’s no point updating your UI if no one can see it. If you need to continue updating or processing in the background, Android provides a Service class designed to run in the background without the UI overheads.
-
Switches seamlessly from the background to the foreground With the multitasking nature of mobile devices, it’s very likely that your applications will regularly switch into and out of the background. When this happens, it’s important that they “come to life” quickly and seamlessly. Android’s nondeterministic process management means that if your application is in the background, there’s every chance it will get killed to free up resources. This should be invisible to the user. You can ensure this by saving the application state and queuing updates so that your users don’t notice a difference between restarting and resuming your application. Switching back to it should be seamless with users being shown the exact UI and application state they last saw.
-
Is polite Your application should never steal focus or interrupt a user’s current activity. Use Notifications and Toasts (detailed in Chapter 8) instead to inform or remind users that their attention is requested if your application isn’t in the foreground. There are several ways for mobile devices to alert users. For example, when a call is coming in, your phone rings; when you have unread messages, the LED flashes; and when you have new voice mail, a small “mail” icon appears in your status bar. All these techniques and more are available through the notification mechanism.
-
Presents a consistent user interface Your application is likely to be one of several in use at any time, so it’s important that the UI you present is easy to use. Don’t force users to interpret and relearn your application every time they load it. Using it should be simple, easy, and obvious— particularly given the limited screen space and distracting user
-
Is responsive Responsiveness is one of the most important design considerations on a mobile device. You’ve no doubt experienced the frustration of a “frozen” piece of software; the multifunction nature of a mobile makes it even more annoying. With possible delays due to slow and unreliable data connections, it’s important that your application use worker threads and background services to keep your activities responsive and, more importantly, stop them from preventing other applications from responding in a timely manner.
next Developing for Android

Related posts :
0 comments for this post
Leave a reply
Microsoft Word LaTeX Shortcut...
05-Nov-2020Learn Python...
23-Mar-2019A Mathematical Theory of Comm...
10-Dec-2015The Free Energy Secrets of Co...
26-Dec-2014Electronic refrigeration usin...
23-Nov-2014
- Radhika says:
Nice. Thanks for the great information. I have read many blogs but this blog is really informative....[[More detail]] - arohi patil says:
Two Stage Transformer Oil Filtration Plant - Jhun05 says:
Hi, i really needineed help,isais there anyone who can help me about this kV2c FM45s GE electric...[[More detail]] - arif says:
You possess lifted an essential offspring..Blesss for using..I would want to study better latest...[[More detail]] - Dilip says:
Very informative blog. thank you for sharing . keep posting.[[More detail]]