1. Welcome
Introduction
In this practical you learn how to install Android Studio, the Android development environment. You also create and run your first Android app, Hello World, on an emulator and on a physical device.
What you should already know
You should be able to:
- Understand the general software development process for object-oriented applications using an IDE (integrated development environment) such as Android Studio.
- Experience in object-oriented programming, with some of it focused on the Java programming language. (These practicals will not explain object-oriented programming or the Java language.)
What you'll need
- A computer running Chrome OS, Windows, Linux, or a Mac running OS X. See the Android Studio download page for up-to-date system requirements.
- Internet access or an alternative way of loading the latest Android Studio and Java installations onto your computer.
What you'll learn
- How to install and use the Android Studio IDE.
- How to use the development process for building Android apps.
- How to create an Android project from a template.
- How to add log messages to your app for debugging purposes.
What you'll do
- Install the Android Studio development environment.
- Create an emulator (virtual device) to run your app on your computer.
- Create and run the Hello World app on the virtual and physical devices.
- Explore the project layout.
- Generate and view log messages from your app.
- Explore the
AndroidManifest.xml
file.
2. App overview
After you successfully install Android Studio, you will create, from a template, a new project for the Hello World app. This simple app displays the string "Hello World" on the screen of the Android virtual or physical device.
Here's what the finished app will look like:
3. Task 1: Install Android Studio
Android Studio provides a complete integrated development environment (IDE) including an advanced code editor and a set of app templates. In addition, it contains tools for development, debugging, testing, and performance that make it faster and easier to develop apps. You can test your apps with a large range of preconfigured emulators or on your own mobile device, build production apps, and publish on the Google Play store.
Android Studio is available for computers running Windows or Linux, and for Macs running macOS. The newest OpenJDK (Java Development Kit) is bundled with Android Studio.
To get up and running with Android Studio, first check the system requirements to ensure that your system meets them. The installation is similar for all platforms. Any differences are noted below.
- Navigate to the Android developers site and follow the instructions to download and install Android Studio.
- Accept the default configurations for all steps, and ensure that all components are selected for installation.
- After finishing the install, the Setup Wizard will download and install some additional components including the Android SDK. Be patient, this might take some time depending on your Internet speed, and some of the steps may seem redundant.
- When the download completes, Android Studio will start, and you are ready to create your first project.
4. Task 2: Create the Hello World app
In this task, you will create an app that displays "Hello World" to verify that Android studio is correctly installed, and to learn the basics of developing with Android Studio.
2.1 Create the app project
- Open Android Studio if it is not already opened.
- In the main Welcome to Android Studio window, click New Project.
- The New Project window appears, prompting you to choose an Activity. An Activity is a single, focused thing that the user can do. It is a crucial component of any Android app. An Activity typically has a layout associated with it that defines how UI elements appear on a screen. Android Studio provides Activity templates to help you get started. For the Hello World project, choose Empty Activity as shown below, and click Next.
- In the next window, enter Hello World for the Name.
- Accept the default com.example.helloworld for the Package name, or create a unique package name. If you are not planning to publish your app, you can accept the default. Be aware that changing the package name of your app later is extra work.
- Verify that the default Save location is where you want to store your Hello World app and other Android Studio projects, or change it to your preferred directory.
- Ensure that the selected language is Java; if it is not, use the dropdown menu to set it.
- Ensure that API 21: Android 5.0 (Lollipop) is set as the Minimum SDK; if it is not, use the dropdown menu to set it.
- Check the option to Use legacy android.support libraries (Note: newer codelabs will leave this unchecked). As of this writing, these settings make your Hello World app compatible with 98% of Android devices active on the Google Play store.
- Click Finish.
Android Studio creates a folder for your projects, and builds the project with Gradle (this may take a few minutes).
Tip: See the Configure your build developer page for detailed information.
You may also see a "Tip of the day" message with keyboard shortcuts and other useful tips. Click Close to close the message.
The Android Studio editor appears. Follow these steps:
- Click the activity_main.xml tab to see the layout editor.
- Click the layout editor Design tab, if not already selected, to show a graphical rendition of the layout as shown below.
- Click the MainActivity.java tab to see the code editor as shown below.
2.2 Explore the Project > Android pane
In this practical, you will explore how the project is organized in Android Studio.
- If not already selected, click the Project tab in the vertical tab column on the left side of the Android Studio window. The Project pane appears.
- To view the project in the standard Android project hierarchy, choose Android from the dropdown menu at the top of the Project pane, as shown below.
2.3 Explore the Gradle Scripts folder
The Gradle build system in Android Studio makes it easy to include external binaries or other library modules to your build as dependencies.
When you first create an app project, the Project > Android pane appears with the Gradle Scripts folder expanded as shown below.
Follow these steps to explore the Gradle system:
- If the Gradle Scripts folder is not expanded, click the arrow to expand it.
This folder contains all the files needed by the build system.
- Look for the settings.gradle (Project Settings) file.
This is where you'll find the project-level repository settings and the modules to include when building your app. The Gradle settings file is part of the standard project structure for an Android app. Most of the time, you won't need to make any changes to this file, but it's still useful to understand its contents.
By default, the settings file uses the pluginManagement
block to configure the repositories Gradle uses to search or download the Gradle plugins and their transitive dependencies. The dependencyResolutionManagement
block configures the repositories and dependencies used by all modules in your project, such as libraries that you are using to create your application. When your dependency is something other than a local library or file tree, Gradle looks for the files in whichever online repositories are specified in the repositories block of this file. By default, new Android Studio projects declare MavenCentral and Google (which includes the Google Maven repository) as the repository locations:
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
}
}
- Look for the build.gradle (Project: Hello_World) file.
In addition to the project-level build.gradle
file, each module has a build.gradle
file of its own, which allows you to configure build settings for each specific module (the HelloWorld app has only one module). Configuring these build settings allows you to provide custom packaging options, such as additional build types and product flavors. You can also override settings in the AndroidManifest.xml
file or the top-level build.gradle
file.
This file is most often the file to edit when changing app-level configurations, such as declaring dependencies in the dependencies
section. You can declare a library dependency using one of several different dependency configurations. Each dependency configuration provides Gradle different instructions about how to use the library. For example, the statement implementation fileTree(dir: 'libs', include: ['*.jar'])
adds a dependency of all ".jar" files inside the libs
directory.
The following is the build.gradle (Module: Hello_World.app) file for the HelloWorld app:
plugins {
id 'com.android.application'
}
android {
compileSdk 32
defaultConfig {
applicationId "com.example.helloworld"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:2.0.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
- Click the arrow to close Gradle Scripts.
2.4 Explore the app and res folders
All code and resources for the app are located within the app
and res
folders.
- Expand the app folder, the java folder, and the com.example.helloworld folder to see the MainActivity java file. Double-clicking the file opens it in the code editor.
The java folder includes Java class files in three subfolders, as shown in the figure above. The com.example.helloworld (or the domain name you have specified) folder contains all the files for an app package. The other two folders are used for testing and described in another lesson. For the Hello World app, there is only one package and it contains MainActivity.java
. The name of the first Activity
(screen) the user sees, which also initializes app-wide resources, is customarily called MainActivity (the file extension is omitted in the Project > Android pane).
- Expand the res folder and the layout folder, and double-click the activity_main.xml file to open it in the layout editor.
The res folder holds resources, such as layouts, strings, and images. An Activity
is usually associated with a layout of UI views defined as an XML file. This file is usually named after its Activity
.
2.5 Explore the manifests folder
The manifests
folder contains files that provide essential information about your app to the Android system, which the system must have before it can run any of the app's code.
- Expand the manifests folder.
- Open the AndroidManifest.xml file.
The AndroidManifest.xml
file describes all of the components of your Android app. All components for an app, such as each Activity
, must be declared in this XML file. In other course lessons you will modify this file to add features and feature permissions. For an introduction, see App Manifest Overview.
5. Task 3: Use a virtual device (emulator)
In this task, you will use the Device Manager to create a virtual device (also known as an emulator) that simulates the configuration for a particular type of Android device, and use that virtual device to run the app. Note that the Android Emulator has additional requirements beyond the basic system requirements for Android Studio.
Using the Device Manager, you define the hardware characteristics of a device, its API level, storage, skin and other properties and save it as a virtual device. With virtual devices, you can test apps on different device configurations (such as tablets and phones) with different API levels, without having to use physical devices.
3.1 Create an Android virtual device (AVD)
In order to run an emulator on your computer, you have to create a configuration that describes the virtual device.
- In Android Studio, select Tools > Device Manager, or click the Device Manager icon
in the toolbar. The Device Manager pane appears. If you've already created virtual devices, the pane shows them (as shown in the figure below); otherwise you see a blank list.
- Click the Create Device button. The Select Hardware window appears showing a list of pre configured hardware devices. For each device, the table provides a column for its diagonal display size (Size), screen resolution in pixels (Resolution), and pixel density (Density).
- Choose a device such as Pixel 5, and click Next. The System Image screen appears.
- Click the Recommended tab if it is not already selected, and choose which version of the Android system to run on the virtual device (such as R).
There are many more versions available than shown in the Recommended tab. Look at the x86 Images and Other Images tabs to see them.
If a Download link is visible next to a system image you want to use, it is not installed yet. Click the link to start the download, and click Finish when it's done.
- After choosing a system image, click Next. The Android Virtual Device (AVD) window appears. You can also change the name of the AVD. Check your configuration and click Finish.
3.2 Run the app on the virtual device
In this task, you will finally run your Hello World app.
- In Android Studio, choose Run > Select Device or click the devices dropdown next to the Run icon
in the toolbar and select the virtual device which you just created.
- Choose Run > Run app or click the Run icon in the toolbar.
The emulator starts and boots just like a physical device. Depending on the speed of your computer, this may take a while. Your app builds, and once the emulator is ready, Android Studio will upload the app to the emulator and run it.
You should see the Hello World app as shown in the following figure.
Tip: When testing on a virtual device, it is a good practice to start it up once, at the very beginning of your session. You should not close it until you are done testing your app, so that your app doesn't have to go through the device startup process again. To close the virtual device, click the X button at the top of the emulator, choose Quit from the menu, or press Control-Q in Windows or Command-Q in macOS.
6. Task 4: (Optional) Use a physical device
In this task, you will run your app on a physical mobile device such as a phone or tablet. You should always test your apps on both virtual and physical devices.
What you need:
- An Android device such as a phone or tablet.
- A data cable to connect your Android device to your computer via the USB port.
- You may need to perform additional steps to run on a hardware device. Check the Using Hardware Devices documentation. You may also need to install the appropriate USB driver for your device. For Windows-based USB drivers, see OEM USB Drivers.
4.1 Turn on USB debugging
To let Android Studio communicate with your device, you must turn on USB Debugging on your Android device. This is enabled in the Developer options settings of your device.
On Android 4.2 and higher, the Developer options screen is hidden by default. To show developer options and enable USB Debugging:
- On your device, open Settings, search for About phone, click on About phone, and tap Build number seven times.
- Return to the previous screen (Settings / System). Developer options appears in the list. Tap Developer options.
- Choose USB Debugging.
4.2 Run your app on a device
Now you can connect your device and run the app from Android Studio.
- Connect your device to your development machine with a USB cable.
- In Android Studio, choose Run > Select device or click the devices dropdown next to the Run button
in the toolbar and select your connected device.
- Click the Run button in the toolbar.
Android Studio installs and runs the app on your device.
Troubleshooting
If your Android Studio does not recognize your device, try the following:
- Unplug and replug your device.
- Restart Android Studio.
If your computer still does not find the device or declares it "unauthorized", follow these steps:
- Unplug the device.
- On the device, open Developer Options in the Settings app.
- Tap Revoke USB Debugging authorizations.
- Reconnect the device to your computer.
- When prompted, grant authorizations.
You may need to install the appropriate USB driver for your device. See the Using Hardware Devices documentation.
7. Task 5: Change the app Gradle configuration
In this task you will change something about the app configuration in the build.gradle (Module: Hello_World.app)
file in order to learn how to make changes and synchronize them to your Android Studio project.
5.1 Change the minimum SDK version for the app
Follow these steps:
- Expand the Gradle Scripts folder if it is not already open, and double-click the build.gradle (Module:Hello_World.app) file.
The content of the file appears in the code editor.
- Within the
defaultConfig
block, change the value ofminSdkVersion
to23
. - The code editor shows a notification bar at the top with the Sync Now link.
5.2 Sync the new Gradle configuration
When you make changes to the build configuration files in a project, Android Studio requires that you sync the project files so that it can import the build configuration changes and run some checks to make sure the configuration won't create build errors.
To sync the project files, click Sync Now in the notification bar that appears when making a change (as shown in the previous figure), or click the Sync Project with Gradle Files icon in the toolbar.
When the Gradle synchronization is finished, the message Gradle build finished
appears in the bottom left corner of the Android Studio window.
For a deeper look into Gradle, check out the Build System Overview and Configuring Gradle Builds documentation.
8. Task 6: Add log statements to your app
In this task, you will add Log
statements to your app, which display messages in the Logcat pane. Log
messages are a powerful debugging tool that you can use to check on values, execution paths, and report exceptions.
6.1 View the Logcat pane
To see the Logcat pane, click the Logcat tab at the bottom of the Android Studio window as shown in the figure below.
In the figure above:
- The Logcat tab for opening and closing the Logcat pane, which displays information about your app as it is running. If you add
Log
statements to your app,Log
messages appear here. - The
Log
level menu is set to Verbose (the default), which shows allLog
messages. Other settings include Debug, Error, Info, and Warn.
6.2 Add log statements to your app
Log
statements in your app code display messages in the Logcat pane. For example:
Log.d("MainActivity", "Hello World");
The parts of the message are:
Log
: TheLog
class for sending log messages to the Logcat pane.d
: The DebugLog
level setting to filter log message display in the Logcat pane. Other log levels aree
for Error,w
for Warn, andi
for Info."MainActivity"
: The first argument is a tag which can be used to filter messages in the Logcat pane. This is commonly the name of theActivity
from which the message originates. However, you can make this anything that is useful to you for debugging.
By convention, log tags are defined as constants for the Activity
:
private static final String LOG_TAG = MainActivity.class.getSimpleName();
"Hello world"
: The second argument is the actual message.
Follow these steps:
- Open your Hello World app in Android studio, and open
MainActivity
. - To add unambiguous imports automatically to your project (such as
android.util.Log
required for usingLog
), choose File > Settings in Windows, or Android Studio > Preferences in macOS. - Choose Editor > General >Auto Import. Select all checkboxes and set Insert imports on paste to Always.
- Click Apply and then click OK.
- In the
onCreate()
method ofMainActivity
, add the following statement:
Log.d("MainActivity", "Hello World");
The onCreate()
method should now look like the following code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("MainActivity", "Hello World");
}
- If the Logcat pane is not already open, click the Logcat tab at the bottom of Android Studio to open it.
- Check that the name of the target and package name of the app are correct.
- Change the
Log
level in the Logcat pane to Debug (or leave as Verbose since there are so few log messages). - Run your app.
The following message should appear in the Logcat pane:
11-24 14:06:59.001 4696-4696/? D/MainActivity: Hello World
Tip: If you are seeing a lot of extra log messages from your emulator, you can use the filter (magnifying glass) to see only log messages that contain MainActivity
.
9. Coding challenge
Challenge: Now that you are set up and familiar with the basic development workflow, do the following:
- Create a new project in Android Studio.
- Change the "Hello World" greeting to "Happy Birthday to " and the name of someone with a recent birthday.
- (Optional) Take a screenshot of your finished app and email it to someone whose birthday you forgot.
- A common use of the
Log
class is to log Java exceptions when they occur in your program. There are some useful methods, such as Log.e(), that you can use for this purpose. Explore methods you can use to include an exception with aLog
message. Then, write code in your app to trigger and log an exception.
10. Summary
- To install Android Studio, go to Android Studio and follow the instructions to download and install it.
- When creating a new app, ensure that API 21: Android 5.0 (Lollipop) is set as the Minimum SDK.
- To see the app's Android hierarchy in the Project pane, click the Project tab in the vertical tab column, and then choose Android in the popup menu at the top.
- Edit the
build.gradle (Module: Hello_World.app)
file when you need to add new libraries to your project or change library versions. - All code and resources for the app are located within the
app
andres
folders. Thejava
folder includes activities, tests, and other components in Java source code. Theres
folder holds resources, such as layouts, strings, and images. - Edit the
AndroidManifest.xml
file to add features, components and permissions to your Android app. All components for an app, such as multiple activities, must be declared in this XML file. - Use the Device Manager to create a virtual device (also known as an emulator) to run your app.
- Add
Log
statements to your app, which display messages in the Logcat pane as a basic tool for debugging. - To run your app on a physical Android device using Android Studio, turn on USB Debugging on the device. Open Settings > About phone and tap Build number seven times. Return to the previous screen (Settings), and tap Developer options. Choose USB Debugging.
11. Related concepts
The related concept documentation is in 1.0: Introduction to Android and 1.1 Your first Android app.
12. Learn more
Android Studio documentation:
- Android Studio download page
- Android Studio release notes
- Meet Android Studio
- Logcat command-line tool
- App Manifest Overview
- Configure your build
Log
class- Create and Manage Virtual Devices
Other:
13. Homework
This section lists possible homework assignments for students who are working through this codelab as part of a course led by an instructor. It's up to the instructor to do the following:
- Assign homework if required.
- Communicate to students how to submit homework assignments.
- Grade the homework assignments.
Instructors can use these suggestions as little or as much as they want, and should feel free to assign any other homework they feel is appropriate.
If you're working through this codelab on your own, feel free to use these homework assignments to test your knowledge.
Build and run an app
- Create a new Android project from the Empty Activity Template.
- Add logging statements for various log levels in
onCreate()
in the main activity. - Create an emulator for a device, targeting any version of Android you like, and run the app.
- Use filtering in Logcat to find your log statements and adjust the levels to only display debug or error logging statements.
Answer these questions
Question 1
What is the name of the layout file for the main activity?
MainActivity.java
AndroidManifest.xml
activity_main.xml
build.gradle
Question 2
What is the name of the string resource that specifies the application's name?
app_name
xmlns:app
android:name
applicationId
Question 3
Which tool do you use to create a new emulator?
- Android Device Monitor
- Device Manager
- SDK Manager
- Theme Editor
Question 4
Assume that your app includes this logging statement:
Log.i("MainActivity", "MainActivity layout is complete");
You see the statement "MainActivity layout is complete" in the Logcat pane if the Log level menu is set to which of the following? (Hint: multiple answers are OK.)
- Verbose
- Debug
- Info
- Warn
- Error
- Assert
Submit your app for grading
Check to make sure the app has the following:
- An
Activity
that displays "Hello World" on the screen. - Log statements in
onCreate()
in the main activity. - Log level in the Logcat pane shows only debug or error logging statements.
14. Next codelab
To find the next practical codelab in the Android Developer Fundamentals (V2) course, see Codelabs for Android Developer Fundamentals (V2).
For an overview of the course, including links to the concept chapters, apps, and slides, see Android Developer Fundamentals (Version 2).