This practical codelab is part of Unit 1: Get started in the Android Developer Fundamentals (Version 2) course. You will get the most value out of this course if you work through the codelabs in sequence.

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:

What you'll need

What you'll learn

What you'll do

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:

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.

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

  1. Open Android Studio if it is not already opened.
  2. In the main Welcome to Android Studio window, click "Start a new Android Studio project".
  3. You will be asked to select a project Template as shown in this image:
    New project template
    and you should select "Empty Activity" and click the Next button.
  4. In the "Configure your Project" window:
    New Project Configuration
    • Enter Hello World for the Application name,
    • Leave the package name as it is,
    • Choose a location to save the project,
    • Ensure that Java is selected as the language,
    • The Minimum SDK can be API 18. If you want to run your app on a physical device that is running an older version of Android, then change this setting to be compatible with your device.

Once you are happy with the settings click Finish

Android Studio creates a folder for your projects, and builds the project with Gradle (this may take a few moments).

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:

  1. Click the activity_main.xml tab to see the layout editor.
  2. The Code, Split and Design buttons at the top right-hand corner allow you to change the display from XML, mixed XML and Screen design, and just design. Select Split:
    Editor window for UI
  3. Click the MainActivity.java tab to see the code editor as shown below.
    Code Editor window

2.2 Explore the Project > Android pane

In this step, you will explore how the project is organized in Android Studio.

  1. 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.
  2. To view the project in the standard Android project hierarchy, choose Android from the popup menu at the top of the Project pane, as shown below.
    File Structure Menu

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.

Gradle Files

Follow these steps to explore the Gradle system:

  1. If the Gradle Scripts folder is not expanded, click the triangle to expand it. This folder contains all the files needed by the build system.
  2. Look for the build.gradle(Project: HelloWorld) file.
    This is where you'll find the configuration options that are common to all of the modules that make up your project. Every Android Studio project contains a single, top-level Gradle build file. 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 top-level build file uses the buildscript block to define the Gradle repositories and dependencies that are common to all modules in the project. 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 JCenter and Google (which includes the Google Maven repository) as the repository locations:
    allprojects {
        repositories {
            google()
            jcenter()
        }
    }
    
  3. Look for the build.gradle(Module:app) 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:app) file for the HelloWorld app:
    apply plugin: 'com.android.application'
    
    android {
        compileSdkVersion 30
        buildToolsVersion "30.0.1"
    
        defaultConfig {
            applicationId "uk.aston.helloworld"
            minSdkVersion 18
            targetSdkVersion 30
            versionCode 1
            versionName "1.0"
    
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }
    
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            }
        }
    }
    
    dependencies {
        implementation fileTree(dir: "libs", include: ["*.jar"])
        implementation 'androidx.appcompat:appcompat:1.1.0'
        implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'androidx.test.ext:junit:1.1.1'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    
    }
    
  4. Click the triangle 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.

  1. Expand the app folder, the java folder, and the uk.aston.helloworld (your package name may be different) folder to see the MainActivity.java file. Double-clicking the file opens it in the code editor.
    Main Activity Java File
    The java folder includes Java class files in three subfolders, as shown in the figure above. The uk.aston.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).
    The file contains the following code:
    package uk.aston.helloworld;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.os.Bundle;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    }
    
  2. Expand the res folder and the layout folder, and double-click the activity_main.xml file to open it in the layout editor.
    Res Layout Folder
    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. Our layout file is called activity_main.xml and it contains the following code:
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

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.

  1. Expand the manifests folder.
  2. 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. Our Manifest contains the following code:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="uk.aston.helloworld">
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>
    

In this task, you will use the Android Virtual Device (AVD) 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 AVD 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.

  1. In Android Studio, select Tools > Android > AVD Manager, or click the AVD Manager icon AVD Manager Icon in the toolbar. The Your Virtual Devices screen appears. If you've already created virtual devices, the screen shows them; otherwise you see the following screen:

Android Virtual Device manager

Click the +Create Virtual Device. 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 ).

Configure Virtual Device

  1. Choose a device such as Nexus 6 or Pixel XL, and click Next. The System Image screen appears.
  2. 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 ).

System Image Selection

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.

  1. 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.

Device configuration Screen

If you find that the emulator does not start correctly, try changing the Graphics option to Software - GLES 2.0 and the Boot Option to Cold boot.

3.2 Run the app on the virtual device

In this task, you will finally run your Hello World app.

  1. Select the virtual device from the menu which you just created.
    Device Selection Menu
  2. In Android Studio, choose Run > Run app or click the Run icon 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.

Nexus 6 Emulator Window

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.

In this final 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:

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:

  1. 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.
  2. Choose USB Debugging.

4.2 Run your app on a device

Now you can connect your device and run the app from Android Studio.

  1. Connect your device to your development machine with a USB cable.
  2. Select your device from the menu (here I've connected my Samsung device):
    Connected Device Menu
    You will need to unlock your device screen and allow USB debugging on your device.
  3. Click the Run button Run icon 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:

  1. Unplug and replug your device.
  2. Restart Android Studio.

If your computer still does not find the device or declares it "unauthorized", follow these steps:

  1. Unplug the device.
  2. On the device, open Developer Options in Settings app.
  3. Tap Revoke USB Debugging authorizations.
  4. Reconnect the device to your computer.
  5. When prompted, grant authorizations.

You may need to install the appropriate USB driver for your device. See the Using Hardware Devices documentation.

In this task you will change something about the app configuration in the build.gradle(Module: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:

  1. Expand the Gradle Scripts folder if it is not already open, and double-click the build.gradle(Module:app) file.
    The content of the file appears in the code editor.
  2. Within the defaultConfig block, change the value of minSdkVersion to 20 as shown below (it was originally set to 18). This change will mean that devices running Android API 19 or lower will not be able to run this app.

Setting the Minimum Sdk Version

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 click Sync Now 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.

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.

Logcat Pane

In the figure above:

  1. 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.
  2. The Log level menu set to Verbose (the default), which shows all Log 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:

By convention, log tags are defined as constants for the Activity:

private static final String LOG_TAG = MainActivity.class.getSimpleName(); 

Follow these steps to add your own Log message to your Hello World app:

  1. Open your Hello World app in Android studio, and open MainActivity.
  2. To add unambiguous imports automatically to your project (such as android.util.Log required for using Log), choose File > Settings in Windows, or Android Studio > Preferences in macOS.
  3. Choose Editor > General >Auto Import. Select all checkboxes and set Insert imports on paste to All.
  4. Click Apply and then click OK.
  5. In the onCreate() method of MainActivity, 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");
    }
    
  6. If the Logcat pane is not already open, click the Logcat tab at the bottom of Android Studio to open it.
  7. Check that the name of the target and package name of the app are correct.
  8. Change the Log level in the Logcat pane to Debug (or leave as Verbose since there are so few log messages).
  9. Run your app.

The following message should appear in the Logcat pane:

07-13 18:08:03.573 29359-29359/uk.aston.helloworld D/MainActivity: Hello World

Challenge: Now that you are set up and familiar with the basic development workflow, do the following:

  1. Create a new project in Android Studio.
  2. Change the "Hello World" greeting to "Happy Birthday to " and the name of someone with a recent birthday.
  3. (Optional) Take a screenshot of your finished app and email it to someone whose birthday you forgot.
  4. 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 a Log message. Then, write code in your app to trigger and log an exception.

The related concept documentation is in 1.0: Introduction to Android and 1.1 Your first Android app.