WHAT'S IN THIS CHAPTER?
Welcome to Android Studio! Whether you are an Eclipse-based ADT veteran or a total newbie to Android development, you will enjoy Android Studio, which is based on IntelliJ IDEA and offers new tools, a UI editor, a whole new build system, memory/CPU analyzers, and many more new features and functionalities.
After long years of the Eclipse-based ADT plugin suite, Google announced (at Google I/O 2014) that Android Studio would be the official supported IDE for Android Development. Of course, you can still use ADT if you are coming from a strong Eclipse background; however, you will probably face problems that you may need to solve on your own.
As an Eclipse committer who has written code for several Eclipse projects, I preferred to stay with ADT for a long time. However, with the announcement that Android Studio is the official IDE, “resistance is futile.”
If you are new to Android development, it may even be easier to adapt to Android Studio because your previous Eclipse experience might not necessarily help you a lot on the IntelliJ platform.
Figure 2.1 shows the welcome screen of Android Studio, which is the first screen you will see when you launch Android Studio. From here, you can start a new project. In this chapter, you will work on a sample project, so let's open an existing project by importing the code.
Numerous sample projects are hosted in GitHub. Because those projects are always up-to-date and new ones are added when a new API or functionality is introduced, it is a good idea to use them as a reference template for your own projects. Plus, all those samples are under the Apache software license, which makes them available to be used freely even in commercial products.
Because everyone loves selfies, in this example you build yet another selfie app.
Keep the Application name and Project location that appear on the Sample Setup screen (see Figure 2.3).
Your project will be downloaded from GitHub, and the main IDE window, which is mostly empty, will appear.
Once you click Finish, Android Studio creates the project and switches to the main development layout. Before you figure out where to find your project files, let's take a look at Android SDK configuration in the following sidebar.
When the SDK installations are complete, you can start working with one of them. As long as your Android project does not make use of a feature that is introduced with a specific version of an SDK, you can easily convert your project to work with an older SDK.
We recommend that you work with the latest version of the SDK to build and compile your project, but use the minSDK
attribute to support the earliest supported version.
We cover build and support versions of the SDK in this and following chapters.
Everything looks great? Well, not exactly because you should probably be looking at an empty screen, as shown in Figure 2.7.
We say that “you should probably be looking at an empty screen” because we want these instructions to remain version agnostic. It is possible that future updates might cause a change and your screen might not be empty.
Although the initial project screen shows nothing about your project, Android Studio gives you a list of hints about how to move to the next step. For this example, press Command+1 on Mac or Alt+1 on Windows to open the project view. The project view, shown in Figure 2.8, displays all the contents of your project.
If you are coming from an ADT background, be aware that Android project structure has changed dramatically with Gradle. With Android Studio, project resources are grouped by types, which does not correspond to their locations on the file system. Although this is a clever approach and is handy, it can also be tricky if you are used to the projects view from ADT.
If you prefer to list resources similar to the way they are hosted in the file system, click the Android list on the top left and a menu with different options will open. Choose Project, and Android Studio will group your project resources as they appear in the file system, as shown in Figure 2.9.
Let's examine this view to gain a better understanding of Android Studio project structure. Every project has a few hidden folders, which you might not be able to navigate with your file manager.
Typically, an Android project has three hidden folders, as listed at the top left of Figure 2.9. The hidden folders are:
Typically, users should not directly edit any file in the hidden folders. Let the IDE deal with them.
Next is the application folder. The name of this folder can change depending on your application name and preferences. However, you can easily recognize the folder because it has a small device symbol on the lower right of the folder icon. This type of folder holds the source code, application files, and configuration.
There can be more than one Application folder in your project depending on its size and architecture. In this chapter we will assume there's one named “app,” but will dig into different combinations in later chapters.
Expand the app folder by clicking the triangle to the left of the folder name. If you have developed Android applications before, the contents should be familiar to you. If not, the following pages give detailed information.
The project folders are:
There are also several files in the root of the project folder. These are essential because they usually affect each module in the project. You may need to edit the following essential project files.
You may find additional files in the root project folder, which you don't need to edit or worry about for now. Although we covered all root level files and folders, we haven't covered the most important one, the src folder.
The src folder hosts all source, resource, and application manifests. Expand the source folder to list its contents, as shown in Figure 2.10.
Inside the src folder is only one folder, which is named main. The main folder contains the java and res folders, which have different icons than other folders to highlight their importance.
The java folder contains all the packages in the format of reverse URL and Java classes. In our example, we have only one package, com.example.android.camera2basic, which has three Java classes. Clicking a class file will open the editor and display the chosen Java file's contents, as shown in Figure 2.11.
We cover the editor in detail but first let's move to the other folder inside main. The res folder holds all resource files, including images, layouts, localization files, and so on. Android projects have different folders for different screen sizes, pixel densities, and other parameters, as shown in Figure 2.12.
Placing different sizes of the same image into a drawable folder will leverage the ability of Android to display the most appropriate image for the device your application is running on. The idea is the same for the layout and values folders. Different layouts can be added for landscape and portrait views, and different values can be added for different versions and pixel densities.
This approach has given Android the capability to run on different screen sizes and densities from the beginning, unlike most other mobile platforms, which used to offer only a fixed resolution.
When you are developing for Android always keep in mind that your application may target very different screen sizes—from phones to tablets, as well as watches, TVs, and even glasses.
Finally, we can focus on one final file that is very trivial for an Android application, the AndroidManifest.xml
file. The Android manifest holds metadata from the list of activities, services, application name and version, target and minimum SDK requirements, and hardware requirements for the target devices, as well as the permissions that your app requires. Listing 2.1 shows the contents of AndroidManifest.xml
.
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2014 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.camera2basic">
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera"/>
<uses-feature android:name="android.hardware.camera.autofocus"/>
<application android:allowBackup="true"
android:label="@string/app_name"
android:icon="@drawable/ic_launcher"
android:theme="@style/MaterialTheme">
<activity android:name=".CameraActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Our manifest file starts with the manifest declaration, which also declares the main package. This declaration enables us to refer to subpackages and classes by using only the suffix after the root package.
Next, the manifest declares the permissions, followed by the uses-feature
tag to declare the hardware requirements of the application.
Every activity and service component that resides in an Android project must be listed under the application
tag. The sample project consists of only one activity, which is used as the entry point of the sample app, so the activity is listed as .CameraActivity
, only with the full path and name after the root package and with the LAUNCHER
intent. This activity will be used for launching the application presented in the Android manifest.
The sample project is a complete and ready-to-run application, so we can move on to building and running the application. Android Studio offers different ways to compile and run projects. To simply build a project, select Build from the toolbar and then the Make Project option, as shown in Figure 2.13.
Although this option will compile and package your app, it will not execute your app on either a device or the emulator. To run the sample project, select Run from the toolbar and then the Run Application option, as shown in Figure 2.14.
Alternatively, you can click the green Play icon (or Control+R on Mac, Ctrl+R in Windows), as shown in Figure 2.15.
Depending on your computer's hardware, Android Studio will spend some time to build the application and later will ask for a target device, which can also be an emulator, to run the application on. You haven't either created a virtual device or connected a real device yet, so you'll do that in the next section.
Android Emulator is a great tool that is bundled with Android Studio. It enables your computer to emulate Android hardware and operating system to run your apps and provide a preview of how it would behave on a real device. The Android emulator enables you to test your application on a variety of screen sizes, hardware configurations, Android versions, and even different CPU architectures.
However, the Android emulator has a bad reputation for being very slow. Developers used to make fun of it by saying, “If you optimize your app for the emulator, it will run smoothly on any device.” This may sound exaggerated but was almost true in the past.
The main performance problem behind the emulation resulted from the ARM CPU emulation on personal computers, which mostly run on x86 CPU architecture. In 2011, Intel introduced HAXM and Google started providing x86-based Android system images, which boosted the emulator performance by using the host CPU instead of emulating a different CPU architecture.
To start using the emulator, you need to install HAXM and the x86 image of the desired version of Android. HAXM requires a minimum version of Android SDK 17. In most cases, HAXM installation is pretty straightforward. If you already installed the SDK (see Chapter 1), you can start creating your virtual device. If you didn't install it, you can set it up with the SDK Manager, as discussed in the “Android SDK Configuration Inside Android Studio” sidebar earlier in this chapter.
sdkextrasintelHardware_Accelerated_Execution_Manager
on Windows, or sdk/extras/intel/Hardware_Accelerated_Execution_Manager/
on Mac.It is very easy to create a new Android device. AVD (Android Virtual Device) Manager is the next icon. It's to the left of the SDK Manager, as shown in Figure 2.17.
A list of available devices appears, as shown in Figure 2.19. At the top of the list are Nexus devices, which are the reference devices released by Google. The rest of the list contains common screen sizes and device properties. You are free to modify any device from the list or even create your own for testing purposes. Creating your own device might be a good idea for testing devices that you don't have access to. In addition to creating virtual devices to simulate phones, AVD Manager also supports tablets, wear, and TV.
Nexus 5X is an ARM-based device. Although selecting ARM will provide more accurate device/virtual device testing, emulating ARM on an x86-based laptop will require additional memory and processing power and will result in performance issues. By installing HAXM, you can have your virtual device run an Intel image to provide better performance.
That is it—you created a virtual device that can run your sample project. To run the emulator, open AVD Manager and click the Play icon shown in the Actions column of the virtual device, as shown in Figure 2.22.
Make sure the Use Host GPU option shown in Figure 2.21 is selected. You can also select the Store a snapshot for faster startup option, which will save the last state of the virtual device and load it from disk when it is launched again.
Depending on your hardware configuration, the emulator may take a while to boot up. The initial bootup will take longer than subsequent launches, which might be close to instantaneous if you have chosen the Store a snapshot for faster startup option.
You now have a new Android device to play with and it didn't cost you a penny.
You have now imported and built your project and created a new Android virtual device. In this section, you learn how to deploy the binary to the virtual device. To do that, you need to know how to connect the two.
Luckily, you won't need to do much; Android Debug Bridge (ADB) will handle all the heavy lifting here. ADB works almost seamlessly to deploy and run your app in a virtual or real device. However, you can always access ADB through your OS's shell and execute commands manually. ADB bridges between your computer and the connected device whether it is a real or a virtual device. Most of the time, you won't need to interact with ADB manually. To use ADB, open a console and type
. You should see something similar to Listing 2.2 followed by the usage and option details.adb
$ adb
Android Debug Bridge version 1.0.32
Revision eac51f2bb6a8-android
…
If the adb
command isn't found, you'll have to add it to your system's path. The adb
executable is located in the sdk/platform-tools
folder.
Given that the emulator you just created is still running, if you execute adb devices
you'll see a list of the devices available over ADB. You can use adb install <apk path>
to install a packaged apk to the connected device. However, because the IDE performs this for you, you won't be using the install
option extensively.
Other useful adb
options are push
and pull
. These commands are used to access the device's file system. The following commands will copy a file from your computer to the device and from your device to the computer:
$ adb push <local> <remote>
$ adb pull <remote> <local>
Eclipse ADT and Android Studio have very different project structures and configurations, but importing projects from Eclipse to Android Studio is very straightforward in most cases.
The first option for migrating your Eclipse project to IntelliJ is to import the project into Android Studio.
The IDE will create the necessary files, including Gradle files, and set up your project.
Once the import is complete, import-summary.txt
will be shown, which displays the results of the migration.
Another way to migrate your project is to export the project from Eclipse. To export from Eclipse, your ADT plugins should be up-to-date.
Although your project is converted to Gradle by the end of this process, the project still needs to be imported to Android Studio for IntelliJ-specific files to be created.
Both methods work on most of Android projects without any problem. However, if you happen to come across a problem in either method, switch to the other method to complete the migration.
This chapter gave you a basic overview of the whole Android Studio project structure, Gradle, and ADB. We have seen how to create and configure virtual Android devices using an emulator and how to run your applications using ADB.
We also covered how to migrate Eclipse ADT-based Android projects to new Android Studio–based Gradle projects.