Chapter 3
IN THIS CHAPTER
Creating an elementary Android app
Troubleshooting troublesome apps
Testing an app on an emulator or a real device
In a quiet neighborhood in south Philadelphia, you might find a maternity shop named Hello World. You can find the store on your way to Pat’s (to get a delicious Philly cheesesteak). You might even take a picture of the store’s sign as a sort of inspiration for the content of this chapter: the Hello World app.
A Hello World app is the simplest program that can run in a particular programming language or on a particular platform. (For an interesting discussion of the phrase Hello World, visit http://www.mzlabs.com/JMPubs/HelloWorld.pdf
.) Authors create Hello World apps to show people how to get started writing code for a particular system.
So, in this chapter, you make an Android Hello World app. The app doesn’t do much. (In fact, you might argue that the app doesn’t do anything!) But the example shows you how to create and run new Android projects.
A typical gadget comes with a manual. The manual’s first sentence is “Read all 37 safety warnings before attempting to install this product.” Don’t you love it? You can’t get to the good stuff without wading through the preliminaries.
When at last you have all the software you need, you’re ready to launch Android Studio and create a real, live Android app.
To start the IDE and create your first app, you start, naturally, at the beginning:
Launch Android Studio.
For details on launching Android Studio, see Chapter 2 of this minibook. To find out how to make the most of your Android Studio experience, see Book 2, Chapter 1.
When you launch Android Studio for the first time, you see the Welcome screen. (See Figure 3-1.) The Welcome screen lists any Android Studio projects that you’ve already created. (Hint: You haven’t created any projects yet.) In addition, you see the version of Android Studio you’re using, which is 3.5.1 for this book.
The Welcome screen also offers you some Quick Start options, such as Start a New Android Studio Project, Open an Existing Android Studio Project, and so on.
In the Welcome screen, select Start a New Android Studio Project.
The Create New Project dialog box appears, as shown in Figure 3-2. You consider two things when creating a new project:
For this example, choose Empty Activity and click Next.
You see the Configure Your Project screen, shown in Figure 3-3. This screen is where you tell Android Studio some of the characteristics of your app, such as
Type My First App in the Name field.
Notice that the Package Name and Save Location fields automatically change to match the name of your app. The wizard strips spaces from both the Package Name and Save Location fields because the presence of spaces would create problems when you compile the app and also causes problems when the IDE looks for the app on the hard drive.
You don’t need to change the other fields for now. However, in a real app, you might. For example, the package name might need to use your domain name instead of com.example
.
The section “The more things stay the same, the more they change” in Chapter 2 of this minibook tells you about API levels. Newer versions of Android generally have more functionality and sometimes fewer problems than older versions do, but more devices run the older versions. A device that currently has Android 8.0 installed can run apps that require Android 8.0 or older. The Configure Your Project screen shows the percentage of devices that are likely able to run your app based on the Minimum API Level setting that you choose.
Click Finish.
Android Studio creates a project that has the characteristics you chose. This process can take a while, so you need to be patient (the status bar will keep you informed as to the setup progress, but even the status bar can take a while to update). It's time to play that game of Solitaire you’ve been wanting for a while now. When the process of creating the project is finished, you see a window similar to the one shown in Figure 3-4. (If you see any informational dialog boxes, you can feel free to dismiss them.)
You’ve started up Android Studio and created your first project. The project doesn’t do much except display Hello world! on the screen. Even so, you can run the project and see it in action. Here’s how you start:
Take a look at Android Studio’s main window.
When Android Studio initially creates your app, you see the MainActivity.kt
(.kt
is the Kotlin code file extension) file. For now, you want to see the activity_main.xml
file, shown in Figure 3-5. Just click its tab (which is left of the MainActivity.kt
tab).
In Android Studio, your new app consumes the entire main window. If, for some reason, more than one Android Studio window is open, make sure that the window you're looking at is the one containing your newly created Android app.
In Android Studio’s main menu, choose Run⇒ Run ‘app’.
If you see an error message saying “Error running ‘app’: No target device found,” it means that you haven’t created an Android Virtual Device (AVD) yet. The steps shown in the “Creating an Android virtual device” section in Chapter 2 of this minibook tells you how to create an AVD. You must have an AVD defined before the emulator will run. The example screenshots (starting with Figure 3-8) show how the app will look in a Google Pixel 3a running Android 10 (Q) with a Portrait startup orientation.
As your application builds, you see messages in the Build Output window, as shown in Figure 3-6. Figure 3-6 actually shows the appearance of this window after the build process completes. Notice that it displays times for each step of the process, a completion message (“Install successfully finished in 10 s 676 ms.”), and a total time. You can even drill down into each of the individual steps to obtain further information.
As activity occurs in the various windows, you see an indicator next to them telling you there is more information. In this case, notice that the success message is associated with the Run window.
Click the Run tab.
You see a list of run events like those shown in Figure 3-7. Notice that the list tells you which parts of the code are running. This information isn’t very useful now, but you’ll find it invaluable later when debugging your app.
It’s also useful to see how well your application is running. A profiler studies your application and determines how well it uses resources and what sort of load it places on the device. Because the profiler is separate from Android Studio, you may see one or more messages from your platform asking whether you want to grant permission to the profiler to perform its task. The next step requires you grant permission, but you can simply skip the next step if desired.
Click the Profiler tab.
You see profiling information similar to that shown in Figure 3-7. Because this app is so simple, the CPU usage remains at 0%, for the most part. In this case, the app is using 42.1MB, there is no network activity, and it’s not even using enough energy to record.
Click the red square in the Profiler window.
Profiling of your app stops.
In this section, you kick your new app’s tires and take your app around the block. Here’s how:
Wait for the Android emulator to display a lock screen, a home screen, or an app’s screen.
What you see depends on the emulator you selected. The process is much like the process used on a real device. You see the initial boot screen, and then a home screen like the one shown in Figure 3-8, and finally the app’s screen, which appears in Figure 3-9. Don’t worry if you have to squint to see Hello World; it’s right there in the center of the screen in incredibly small letters.
Along with the emulator presentation of the device, you get controls for interacting with that device, as shown in Figure 3-9. Notice that you can turn off the device, mute the sound, rotate it in various ways, and interact with features like the camera and buttons.
We can’t overemphasize this point: Wait for the Android emulator to display a lock screen, a home screen, or an app’s screen.
Android’s emulator takes a long time to start. For example, on a system that has a 2.6 GHz processor with 8GB of RAM, the emulator takes a few minutes to mimic a fully booted Android device. Some people blame the fact that it’s an emulator instead of a simulator. (See Chapter 2 of this minibook for that argument.) Others claim that the translation of graphics hogs the emulator’s time. For whatever reason, you need lots of patience when you deal with Android’s emulator.
The device loading time seems to decrease after the first time you load it. This is because the emulator saves state information that it uses to load the device again later. The state information consumes more disk space on your system but also reduces loading time, so it’s a good trade-off.
Keep waiting.
While you’re waiting, you might want to visit https://www.genymotion.com/
. For information on Genymotion’s alternative to the standard Android emulator, see Chapter 2 of this minibook.
Oh! We see that your emulator is finally displaying the lock screen. It’s time to proceed …
If the emulator displays the lock screen, do whatever you normally do to unlock an Android device.
Normally, you perform some sliding or swiping motion.
See your app on the emulator’s screen.
Figure 3-9 shows the running of Android’s Hello World app. (The screen even has Hello World! on it.) Android’s development tools create this tiny app when you create a new Android project. Android’s Hello World app has no widgets for the user to push, and the app doesn’t do anything interesting. But the appearance of an app on the Android screen is a very good start. By following the steps in this chapter, you can start creating many exciting apps.
When you are finished working with the emulator, click the Close button (the X on top of the controls shown previously in Figure 3-9). If you click the Power button, the emulator continues to run; it just emulates the device being turned off.
Throughout this book, you discover how to create apps that illustrate Android development principles using a simple process. “First, type this code; next, type that code; and so on,” says the book. You can follow the instructions in each and every chapter, but you can also bypass the instructions. You can scoop the book’s examples from a special website. Here’s how:
http://www.allmycode.com/android
or https://users.drew.edu/bburd/android/
.Click the link to download this book’s code.
When the download completes, you have a .zip
file (otherwise known as a compressed archive file).
Unzip the downloaded file.
“Unzipping” is the same as “uncompressing” or “expanding.” On some computers, this unzipping happens automatically as soon as the download is finished. On other computers, you unzip the file by clicking (or double-clicking) the file's icon. On still other computers, you right-click or Ctrl-click the downloaded file’s icon and select an unzip (or uncompress or expand) option in the resulting context menu.
For more information about .zip
files, see the sidebar “Compressed archive files.”
After unzipping the file, you have a folder that contains several subfolders. These subfolders have names like 01-05-03
. The folder with the name 01-05-03
contains the third example that appears in Book 1, Chapter 5.
Launch Android Studio.
For details, see Chapter 2 in this minibook.
What you do next depends on what you see when you launch Android Studio.
If you see Android Studio's Welcome screen, select Open an Existing Android Project.
The Open Project dialog box appears.
You start in your personal folder on most operating systems, so you may have to look around on your hard drive if you placed the .zip
folder somewhere else.
If you see Android Studio’s main window, choose File⇒ Open in the main menu.
The Open File or Project dialog box appears.
In either dialog box, navigate to the folder containing the project that you want to open.
For example, to open the third project in Book 1, Chapter 5, navigate to the 01-05-03
folder that's within the unzipped version of the files you downloaded.
Whatever folder you select, look in that folder for a file named build.gradle
.
The build.gradle
file appears in the project's main folder. Figure 3-10 shows the location of this file for the project you built in the “Starting the IDE and creating your first app” section of this chapter. It will be in the same location for the downloadable source.
Highlight the build.gradle
file and click OK.
Android Studio opens as normal. In the Sync tab, shown in Figure 3-11, you see messages telling you the progress of the import process. As each step completes, you see a green check mark placed next to it.
The sync process can take a while to complete, so just watch pet videos while you wait. Android Studio has to download the default Gradle wrapper from the Internet unless you have downloaded and installed the offline tools (see Chapter 2 of this minibook for details). Make sure that you have an Internet connection when you perform this step.
If you’re missing something that the project needs on the host system, you see error messages from Android Studio as the import process progresses. It often pays to wait until the process is complete so that you can see all the error messages rather than trying to fix them one at a time.
You can tell everyone that you created the project from scratch. We won't snitch.
You try to run your first Android app. If your effort stalls, don’t despair. This section has some troubleshooting tips.
You’ve created a project with a certain target SDK or told the IDE to compile with a certain API level. But you haven’t installed that API level. If Android Studio displays a link offering to Install Missing Platform(s) and Sync Project, click the link. Otherwise, open the Android SDK manager and install that API level. For details, see Chapter 2 in this minibook.
You must have at least one AVD configured before an app can run. In addition, the AVD must be able to support the app. Use the steps in the “Creating an Android virtual device” section of Chapter 2 of this minibook to fix this problem.
This message probably means that you haven’t created an AVD capable of running your project. If Android Studio offers to help you create a new AVD, accept it. Otherwise, open the AVD Manager to create a new AVD. For information about Android Virtual Devices and the AVD Manager, see Chapter 2 of this minibook.
The Android Debug Bridge (ADB) connects your development computer to a device that’s executing your new Android code. (The ADB also “connects” your development computer to a running emulator, even though the emulator is running on your development computer.)
If you see a message that hints of ADB trouble, try restarting your development computer’s Android Debug Bridge. Here’s how:
Click the Terminal tool button at the bottom of Android Studio’s main window.
Congratulations! You just opened Android Studio’s Terminal tool window. If you’re a Mac or Linux user, you see the shell prompt. If you’re a Windows user, you see the Windows command prompt.
In the Terminal tool window, go to your ANDROID_HOME/platform-tools
folder.
For help finding your ANDROID_HOME
folder, see the “Installing Android Studio” section in Chapter 2 of this minibook.
In the ANDROID_HOME/platform-tools
folder, type the following two commands:
Windows:
adb kill-server
adb start-server
Macintosh and Linux:
./adb kill-server
./adb start-server
For more information about the Android Debug Bridge, refer to see Book 1, Chapter 2.
In Chapter 2 of this minibook, you create an AVD. And, since the old Chapter 2 days, you may have created some additional AVDs. Now, when you launch an app, your computer fires up one of the many AVDs that you created. That’s fine, but what if the computer fires up your least-favorite AVD? To get control over which AVD starts up, do the following: In Android Studio’s main menu, choose Run⇒ Select Device. A context menu like the one shown in Figure 3-12 appears. The menu allows you to choose any of the devices you have created.
If you don’t see the device you want to use, perhaps you haven’t created it yet or accidentally deleted it. Choose Open AVD Manager in this case to create the device you want to use.
The Troubleshoot Device Connections option sees use only with devices you connect to your system using a USB connection. Selecting this option displays the Connection Assistant, which begins by scanning your system for USB devices that could be Android compatible. Just follow the directions the Connection Assistant provides to ensure that your system can see the device and to install appropriate drivers when it can’t.
After five minutes or so, you don’t see Android’s lock screen or Android’s home screen. Here are several things you can try:
Run your app on a real Android device. Testing a brand-new app on a real device makes us queasy. But Android’s sandbox is fairly safe for apps to play in. Besides, apps load quickly and easily on real phones and tablets.
For instructions on installing apps to real Android devices, see the section “Testing Apps on a Real Device,” later in this chapter.
If you see this message, some tangle involving the emulator keeps Android from doing its job. First try closing and restarting the emulator.
If a simple restart doesn’t work, try the following steps:
In the Actions column, click the tiny downward-pointing arrow associated with that AVD. (See Figure 3-14.)
A context menu appears.
In the context menu, select Wipe Data.
A pop-up dialog box appears. The dialog box asks you to confirm the wiping of the AVD’s data.
In the Confirm Data Wipe pop-up dialog box, click Yes.
The pop-up dialog box disappears (as you thought it would).
In the Actions column, click the right-pointing arrow (the arrow that looks like a Play button).
As a result, Android Studio launches a new copy of the emulator, this time with a clean slate.
To read about the Android Virtual Device (AVD) Manager, see Chapter 2 in this minibook.
If the preceding set of steps doesn’t work, take a firmer approach, as follows:
In your user home folder, look for a folder named .android
(starting with a dot).
For tips on finding your user home folder, see Chapter 2 in this minibook.
From the .android
folder, drill down even deeper into the avd
folder.
The avd
folder contains a folder for each AVD that you've created.
Drill down one more level to the folder for the AVD that’s giving you trouble.
For example, if you were running an AVD named Pie1 when you saw the Data Image Is Used by Another Emulator message, navigate to your Pie1.avd
folder.
.lock
.Android looks for AVDs in your home folder's .android/avd
subfolder, and occasionally Android’s search goes awry. For example, consider that your Windows computer lists the home folder on an i
drive. The AVDs are in i:Users
<user name>
.androidavd
. But Android ignores the computer's home folder advice and instead looks in c:Users
<user name>
. When Android doesn't find any AVDs, Android complains.
You can devise fancy solutions to this problem with junctions or symbolic links. But fancy solutions require special handling of their own. To keep things simple, you can simply copy the i:Users
<user name>
.android
folder's contents to c:Users
<user name>
.android
. That fixes the problem.
The formal name for this dialog box is the Application Not Responding (ANR) dialog box. Android displays the ANR dialog box when an app takes too long to do whatever it’s supposed to do. When your app runs on a real device (a phone or tablet), the app shouldn’t make Android display the ANR dialog box. (Other chapters in this minibook give you tips on how to avoid the dialog box.)
But on a slow emulator, a few ANR boxes are par for the course. When you see the ANR dialog box in an emulator, the best idea is to select Wait. Within about ten seconds, the dialog box disappears and the app continues to run.
Your app runs and you want to make a few improvements. So, with the emulator still running, you modify your app’s code. But after choosing Run⇒ Run ‘app’, the app’s behavior in the emulator remains unchanged.
When this happens, something is clogged up. Close and restart the emulator. If necessary, use the Wipe User Data trick that we describe in the section “Error message: The user data image is used by another emulator,” earlier in this chapter.
You can bypass emulators and test your apps on a phone, a tablet, or maybe an Android-enabled refrigerator. To do so, you have to prepare the device, prepare your development computer, and then hook together the two. This section describes the process.
The simplest way to test your app on a real device is to connect the device to your development computer using a USB cable. Not all USB cables are created equal. Some cables have wires and metal in places where other cables (with compatible fittings) have nothing except plastic. Try to use whatever USB cable came with your Android device. If, like us, you can’t find the cable that came with your device or you don’t know which cable came with your device, try more than one cable. When you find a cable that works, label that able cable. (If the cable always works, then label it stable, able cable.)
To test your app on a real device, follow these steps:
Connect the device you want to use to your computer using the USB cable.
You could connect your device later in the process, but doing it now can save you a lot of time and effort when it comes to ensuring that the connection works. If necessary, tell your device that it’s okay to connect to the host computer for USB transfer.
On your Android device, find the USB Debugging option:
Now your Android device displays the Development list (a.k.a. the Developer Options list).
In the Development (or Developer Options) list, turn on USB debugging.
Your device may display a warning message. For example, here’s what a Q device displays when someone messes with this setting:
USB debugging is intended for development purposes. Use it to copy data between your computer and your device, install apps on your device without notification, and read log data.
The stewards of Android are warning that the USB Debugging option can expose a device to malware.
Theoretically, you can keep USB Debugging on all the time. But if you’re very nervous about security, turn off USB Debugging when you’re not using the device to develop apps.
http://developer.android.com/sdk/oem-usb.html
to download your device’s Windows USB driver. Install the driver on your development computer.http://developer.android.com/guide/developing/device.html
and follow the instructions that you find on that page. (Don’t worry. To connect a device, you don’t have to recompile the Linux kernel.)On your development computer, choose the connected device.
To do this, follow the instructions in the earlier section “You don’t like whatever AVD opens automatically.” The name of your device should appear in the list. However, in some cases, you may see something generic, like Unknown Device or ASUS P027. The point is that the Select Device context menu shown previously in Figure 3-12 will now have another entry in it.
Make sure that your Android device’s screen is illuminated.
This particular step might not be necessary, but some developers have scraped so many knuckles trying to get Android devices to connect with computers that they want every advantage they can possibly get.
Choose Run⇒ Run ‘app’.
You see the build process proceed as normal, and then the Run tab opens and you see communication occur between Android Studio and your device. Finally, you see the app running on your device (rather than on the emulator).
35.170.81.33