Activities and icons in the Android application life cycle

Activities and icons in the Android application life cycle

Add navigation style to your Android mobile app

The Activity class is the foundation of Android mobile applications, and you can use it to optimize the interaction of your application with users and mobile devices. Make the interactions in the application life cycle exactly the way you expect, and use icons and action bars to guide users to use UI navigation and other application functions.

Introduction

About this series

Mobile application releases have exploded in recent years, and so has the market for mobile development technologies. This series of articles will introduce the evolution of mobile applications to developers who are familiar with programming but new to mobile technologies. It starts with coding native applications using Java™ code, and then expands the toolkit to include JVM languages, scripting frameworks, HTML5/CSS/JavaScript, third-party tools, and more. This series of articles will take you step by step to master these necessary technologies to handle all mobile development scenarios.

  • Part 1: Introduction to Android
  • Part 2: Just swipe! Coding gestures in Android
  • Part 3: Activities and Icons in the Android Application Lifecycle

Today's mobile devices are incredibly powerful, far more powerful than the desktop computers that many developers used to write their first programs. As a result, it's easy to forget that mobile devices are still resource-constrained environments. When developing mobile applications, it's important to remember the limitations of the environment in which your application will run. This is especially true when your application is competing for system resources with other applications—some of which are more important to the user's daily behavior than your application.

One way to ensure your app is popular is to make sure it conserves system resources. In Android, the mechanism for using and maintaining system resources is Activity class. The more you understand the life cycle of this fundamental class (which is very similar to a Java Servlet ), the better you will be able to tune the resource usage and performance of your Android mobile app.

We'll start with a quick look at Activity class lifecycle. Working through a sample app, you'll learn the methods that handle each stage of the Android application lifecycle. Once you understand how these methods work together, you can use system resources wisely. Then, we'll update the demo app's navigation system to use action icons instead of menu buttons for user interaction. Icons are pretty standard in mobile app UIs, and newer Android devices (versions 4.2.2 and higher) have deprecated the options menu in favor of the action bar. Understanding how to integrate these features with your Android mobile app will pay off!

Activity class life cycle

The life cycle of Activity maps directly to the life cycle of an Android mobile application. As the user interacts with the application or the device on which the application is running, the Android platform executes callbacks on Activity instance. When the user launches the application, the initial Activity executes a defined life cycle. When the application goes to the background, it executes a different phase of the life cycle, and when the application is closed, it executes another phase. Figure 1 shows the Android Activity life cycle at each stage of interaction.

Figure 1. Android Activity life cycle

The Android mobile application life cycle consists of four stages:

  • start up
  • Pause and resume
  • Stop and restart
  • destroy

The following content will describe each stage and its callback method (which can be implemented inside Activity instance).

Startup in the Activity life cycle

Demo Application

If you have been following this series, you have already created your own demo application in the first and second articles in this series. If you do not have a demo application, I recommend that you create one before continuing. Alternatively, you can clone the Git repository of my own Overheard Word demo application.

In the previous article, you have used the callback method corresponding to starting Activity , namely onCreate . You may also be familiar with onStart and onResume , which are also called at startup. Now, consider these methods in the context of Activity lifecycle.

In the Eclipse Android development environment, you can easily override methods by selecting the Override/Implement Methods... option, as shown in Figure 2.

Figure 2. Overriding Activity lifecycle callback methods

Next, select onStart and onResume methods:

Figure 3. Select callback

Now add some tracing statements using Android's Log class, as I did in Listing 1.

Listing 1. Implementing the Android Activity callback

  1. @Override  
  2. protected   void onResume() {
  3. super .onResume();
  4. Log.d( "overheardword" , "onResume Invoked" );
  5. }
  6.  
  7. @Override  
  8. protected   void onStart() {
  9. super .onStart();
  10. Log.d( "overheardword" , "onStart Invoked" );
  11. }

Check the results by starting an instance of the application and viewing the logs through LogCat, as shown in Figure 4.

Figure 4. Debug statements in LogCat

Android uses LogCat to record logs

Android has its own logging system, android.util.Log . With this convenient class, you can record logs at various levels (such as info , warn , debug , etc.), and then view the logs through the logcat tool that comes with the Android SDK. In Eclipse, you should see LogCat as a tab, which you can use to filter tags and application instances. LogCat also supports accessing logs on the device, as long as the device is plugged into the USB port of a desktop or laptop.

As you've probably guessed, onCreate is called when the app is first loaded, but onStart and onResume are more convenient to use in the context of other stages, such as when the app is backgrounded and restarted.

Pause and resume in the Activity life cycle

Because mobile devices often run multiple applications that compete for the user's attention in various ways, your application should know when to let another application occupy the device screen and use more resources. Sometimes, the user needs to answer a phone call while using your application, or the application may pop up a dialog box, such as an information request or an error message. Each of these actions will partially block the current Activity .

When an Activity is partially blocked, the onPause method is called. When the paused Activity regains focus, onResume is called. Pause and resume means that the affected activity is partially blocked, not completely hidden.

When the application is completely hidden, such as when the user makes a phone call, onPause is also called, but in this case onStop continues to be called. When the application is brought to the foreground again, onRestart is called first, then onStart , and finally onResume .

Here's what happens when you implement onPause , onRestart , and onStop . If you already have the Android app used in this series of articles, add some logging statements to your code and run the app. Press the Home button to hide the instance completely, then click its icon to run it again. You should see a series of methods called. The first you'll see is onPause , then onStop . When you click the icon to rerun the app, the methods called are onRestart , onStart , and onResume , in that order.

Destroying Activity is also something that happens during the normal process of running an application. For example, you can call finish method of Activity instance to terminate the instance. The key here is that because an Activity is closed, it will follow the same life cycle as if it was hidden, but it will finally call back onDestroy .

In Listing 2, I demonstrate this process using my Overheard Word application by calling the finish method on the upward swipe gesture.

Listing 2. Destroying an Activity instance

  1. public   boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
  2. try {
  3. final SwipeDetector detector = new SwipeDetector(e1, e2, velocityX, velocityY);
  4. if (detector.isDownSwipe()) {
  5. return   false ;
  6. } else   if (detector.isUpSwipe()) {
  7. finish();
  8. } else   if (detector.isLeftSwipe()) {
  9. Toast.makeText(getApplicationContext(), "Left Swipe" , Toast.LENGTH_SHORT).show();
  10. } else   if (detector.isRightSwipe()) {
  11. Toast.makeText(getApplicationContext(), "Right Swipe" , Toast.LENGTH_SHORT).show();
  12. }
  13. } catch (Exception e) {
  14. //nothing  
  15. }
  16. return   false ;
  17. }

The most commonly used Activity lifecycle methods are onCreate , onRestart , and onDestroy . For example, I use onRestart to refresh one of the many aspects of the application UI view, and use onDestroy to release the connection to the database, such as SQLite running locally on the Android device.

It may not be obvious now, but once you start working with external resources—such as an external Web service or a device's file system or database—these lifecycle phases become very important.

Next, we will explain how to use two Activity hook methods— onCreateOptionsMenu and onOptionsItemSelected —to implement the application menu behavior. After synchronizing these two methods, we will connect their functionality to the icon to implement additional UI effects.

Navigating using menus and actions

When I created the Overheard Word project in Eclipse, the first Activity defined had a stub method called onCreateOptionsMenu . As you might guess, this method is used to create an options menu. On older Android devices, the options menu was represented by a Menu button. On newer devices, it is represented as a series of vertical dots that appear within the application itself. Newer Android devices may or may not have a Menu button.

In the simulator instance that represents the old device, there is a button called "Menu." When you click it, the application instance displays a menu of options. In this example, we'll see options for navigation. For example, if the user presses the Home button, you'll see something like Figure 5.

Figure 5. An unimplemented menu item

There is no menu button on tablets. Instead of selecting items from a menu , users are required to initiate various actions . This newer UI bar is called the action bar , as shown in Figure 6.

Figure 6. Android's new action bar

Although the menu button behaves in a similar way to the action bar, the action bar is only implemented on newer devices. Since we are targeting older versions of Android (remember, about 50% of Android devices run Gingerbread!), I will demonstrate using the more familiar menu button. Later, I will explain how to update the navigation code to implement the action bar if you want to target newer versions of Android and corresponding devices.

Creating an options menu

In order to refurbish Overheard Word to improve the efficiency of user interaction, the first step is to implement an options menu so that users can exit the application. Exiting the application is one of the stages of Activity life cycle, so we will use Activity methods to implement this function.

Remember, in an Android application, all UI-related business corresponds to an XML file, so the way to define the UI is to edit the layout XML file. The XML files of an Android application are located in a specific directory in the res folder of the project (for example, the layout file is located in the layout directory).

For a quick exercise, take a look at the default implementation of onCreateOptionsMenu method in the Overheard Word main activity—what do you see?

  1. public   boolean onCreateOptionsMenu(Menu menu) {
  2. getMenuInflater().inflate(R.menu.overheard_word, menu);
  3. return   true ;
  4. }

If you're thinking about looking for an XML file called overheard_word.xml in the menu resources directory, then you're not far from becoming an Android expert!

I... quit!

Next, we will edit the menu resource XML file and add a menu item called quit . To begin, you need to find the strings.xml file in your res/values ​​directory. Once you have found it, create a new item like this:

<string name="quit_menu">Quit</string>

This tag defines the word Quit , which can be referenced by the identifier quit_menu (which, by the way, is great for internationalizing your application). Next, open the overheard_word.xml file in menu directory. In this file, change the title to @string/quit_menu , thereby linking the word Quit to the menu item.

Now, start the simulator and press the Menu button. You should see a menu appear at the bottom of the screen with one option: Quit . But selecting it will have no effect, because it is not yet implemented.

We'll add the implementation code for the Quit option in a minute. But first, let's consider another important element of any functional part of a mobile app, its appearance. You may have noticed that a lot of mobile UIs today (and even more and more web app UIs) use icons for navigation. Here's how to replace generic word buttons with free icons.

Icons in Mobile UI Design

Before I got into mobile development, I dabbled in icons, but rarely used them in my enterprise applications. When web applications started to become more interactive, I found myself using icons more often. But it wasn't until I started working in mobile development that icons really became a focus of my work.

Where is my icon?

It's easy to find free icons for use in open source and commercial applications these days. You can also pay a small fee to purchase the rights to use certain icons. I personally like a package called Glyphish that has hundreds of icons to choose from, and the licensing fee is very reasonable. Glyphish also offers a free license. I recommend that you quickly search and find the icons you want to use for the demonstrations in this article.

If you use icons in your Android mobile UI design, you need to be fully aware of the device resolution. The Android device ecosystem is huge, and your application may need to run on a variety of devices, from low-resolution small-screen devices to high-resolution tablets with large 7-inch screens. An icon that looks good on a handheld device may look very rough on a tablet.

Fortunately, you can control how your app icons look on different devices. Take a quick look at the res directory of your Android mobile app. You should see a number of directories named drawable-something-pdi (where "something" is an arbitrary sequence of letters). These directories correspond to various device screen resolutions. Placing correctly sized icons and other image files in these directories will ensure that your icons display correctly on different types of devices.

For example, for devices with very high resolutions, Android will use icons from the drawable-xxhdpi directory. Launch icons in this directory should be 96 x 96 pixels and at least 320 dpi. Launch icons in the drawable-ldpi directory should be 36 x 26 pixels and 120 dpi. You can also choose to create a default drawable directory that Android will use if it cannot find a file for a specified icon resolution.

To keep things simple, I will create a drawable directory for my Overheard Word application. In this directory I place a 26 x 26 icon file (.png format) for the exit option.

Figure 7. Adding an icon to the drawable directory

My next step was to reference the icon in the options menu by updating menu item in my overheard_word.xml file as follows:

  1. android:icon = "@drawable/quit_icon"  

If you followed my steps closely, you should update id of the same element. Give it a descriptive string value, like this:

  1. android:id = "@+id/quit_item"  

It's helpful to use a descriptive, understandable string value when we move on to the next step, implementing the quit behavior inside onOptionsItemSelected method. We'll be able to reference the menu item in the selection event by quit_item ID. Now start the simulator and press the Menu button. I think you'll like what you see!

Figure 8. Nice icons! (Provided by Glyphish)

Implementing menu behavior

Now I have a nice-looking icon that I can use for the Quit menu item (and I hope you have an icon for your own applications, too), but I still need to add the code that tells the application what to do when the button is pressed.

Implementing any behavior in the options menu starts with overriding the onOptionsItemSelected method. So override that method, and then update the code to look like the following (but remember to adjust the menu item IDs for your own application):

Listing 3. Handling menu item selection

  1. public   boolean onOptionsItemSelected(MenuItem item) {
  2. switch (item.getItemId()) {
  3. case R.id.quit_item:
  4. this .finish();
  5. return   true ;
  6. default :
  7. return   super .onOptionsItemSelected(item);
  8. }
  9. }

Note that this is just a simple switch statement. If id of quit_item is selected, finish method will be called to close the application.

Try this new code in the simulator: press the Menu button, choose the Exit ( X ) option, and watch what appears in LogCat. You should see a complete Activity lifecycle, divided into the following stages: onPause , onStop , and onDestroy .

Action Bar in Android 3.x

As mentioned earlier, newer versions of Android (Honeycomb and later) use an action bar instead of an options menu. Newer devices may not even have a Menu button, so understanding the app's navigation (or other functionality) can also be done in the action bar.

It doesn't take a lot of work to ensure that the navigation functionality you implemented by coding for the options menu also works with the action bar. You have already implemented all the required methods, and the only work left is to make some changes to the XML source file.

First you need to create an emulator instance that simulates a device that uses an action bar instead of a menu button. The simplest way to do this is to emulate a tablet. Start the Android SDK Manager command-line application (the android command in the tools directory) in your Android SDK installation. Once the SDK Manager is up and running, select the Manage AVDs... option from the Tools menu. This will display a dialog in which you can define a new emulator or Android Virtual Device (or AVD). Select 7.0'' WSVGA (Tablet) (1024 x 600: mdpi) and then target the emulator to at least Android 4.2.2 . Once you're done, you have an emulator that doesn't respond to the menu button, as shown in Figure 9.

Figure 9. Creating a tablet emulator

Next, launch your app in the tablet instance. You should see a vertical line of three dots in the lower right corner. It looks great, right? By default, Android preserves the menu behavior even on newer display devices. You can upgrade the look and behavior of the action bar to be more natural by updating your app's XML resources.

Start with your app's AndroidManifest.xml file, where you'll update the SDK target:

  1. <uses-sdk android:minSdkVersion= "11" android:targetSdkVersion= "17" />

Next, go to your project's Properties page in Eclipse and update the Project Build Target to any Android version higher than Android 4.2.2. Click OK and let the project rebuild. Then find the menu XML file in menu directory. Update its content as shown below, which will keep the Quit item definition.

  1. android:showAsAction= "always"  

Finally, if your project does not already have two subdirectories named values-v11 and values-v14 under the res directory, create them. Next, add the following XML file to the values-v11 directory:

  1. <resources>
  2. <style name= "AppBaseTheme" parent= "android:Theme.Holo.Light" ></style>
  3. </resources>

In values-v14 directory, add this file:

  1. <resources>
  2. <style name= "AppBaseTheme" parent= "android:Theme.Holo.Light.DarkActionBar" ></style>
  3. </resources>

Now restart the simulator and your new icon should appear in the top right corner:

Figure 10. An action bar with icons

Now go back to the menu file in menu directory (where the quit item is defined) and change showAsAction to never . Rerun your application and you should see the three vertical dots in the upper right corner.

Don't forget to reset

Note that if you want to keep your application targeting Gingerbread, you will need to re-target your project and undo the changes you made to the XML files in this section. These changes are not backwards compatible!

More fun with icons

So far, you've added a menu option to an application targeting Gingerbread, seen it translate beautifully to new devices that implement the action bar, and learned how to upgrade that functionality with a few updates to the application's XML files if you choose to do so.

Now, let's summarize what you've learned about icons. You've already done the main work of adding an icon for your app's navigation menu, so updating its main icon shouldn't be a problem. This icon represents your app to users, so it's important to know how to update and customize it.

I'm going to update Overheard Word's icons, and you can do the same for your own applications. Again, a quick search on the Internet will yield a plethora of icon sites. Among these sites, I found an interesting collection of icons, and one that I really liked:

Figure 11. A beautiful new icon

[[120663]]

Recall that this icon renders differently on different device profiles. I wanted to ensure that users had a good first impression of Overheard Word, so it was imperative that the icon resolution be appropriate for the range of devices I was targeting. Luckily, I knew of a really great site that could help me achieve this goal.

Investment Icon

There's nothing wrong with using free icons for demonstration purposes, but investing in custom icons for a professional app is absolutely necessary. Your icon (or icon set) represents your app's brand, and you want it to be unique. If it's generic, or looks decidedly amateurish, what conclusions will users draw about your app?

Android Asset Studio is a Google Code project that has a ton of useful tools to help Android developers. One tool I use a lot is Launcher Icons. All I have to do is click on the Launcher Icons link and upload my icon. The utility generates the correct sized icon files for various device profiles, which I can then download as a zip file. The file contains four directories, each containing a specific resolution and size version of the file I uploaded.

Figure 12. Launcher Icons creates correctly sized icons for Android.

Next, I copied the ic_launcher.png files in each directory into the same subdirectory of my application's res folder. Note that in this process I may replace the original icon files generated by Eclipse.

Finally, I run the app again and wait for it to appear in my simulator instance. I click the Home button and look at the result: a beautiful app icon that (to me) signals that OverHeard Word is the most interesting app on any user's device!

Figure 13. Now it becomes very vivid!

Conclusion

In this article, you learned about Activity lifecycle and how to use it to improve your app's use of device resources. You also learned how to define and implement navigation widgets using menus and action bars, and how to replace word buttons with icons.

Everything you've learned in this article is essential for building Android applications. Mobile development on Android is easy to pick up and certainly fun, but I want you to understand that it's a different paradigm from the Java development you're familiar with. There are thousands of apps in Google Play and other app stores, so it's usually the well-planned, carefully designed, and cleverly coded ones that make it to the top. There's still a lot to learn!

<<:  Apple Watch UI Animation Analysis

>>:  Mobile technology for the masses: words and gestures from the Overheard Word

Recommend

Feng Qingyang's "Stock Market Practice" Stock Trading Training Lecture No. 2

Training course content: Maybe you spent a lot of...

A complete breakdown of the strategy for creating explosive products!

Ask a question I have come into contact with many...

Growth Case丨Designing a growth experiment for Keep

Growth is a process of continuous experimentation...

Tips for Protocol-Oriented Programming (POP) in Swift

1. Entrustment Model 1. Usage process The most co...

How much does it cost to enter Baidu Procurement for one year?

The past 10 years have been the fastest-growing d...

Analysis of competitors of Xigua Video, Tik Tok, and Kuaishou!

01 Market Analysis 1.1 Market Definition There is...

Analyze product operations based on the AARRR model

The pirate model is often used in product operati...

After this fall, iTunes may no longer exist.

iTunes has never been a good tool, and after year...

What is "fighting fire with fire"?

As of 8:30 a.m. on August 26 Through joint effort...