Quantcast
Channel: Kodeco | High quality programming tutorials: iOS, Android, Swift, Kotlin, Unity, and more
Viewing all articles
Browse latest Browse all 4370

Beginning Android Development with Kotlin, Part One: Installing Android Studio

$
0
0

Update Note: This Beginning Android Development tutorial is now up to date with the latest version of Android Studio, version 3.0, and uses Kotlin for app development. Update by Joe Howard. Original tutorial by Matt Luedke. Previous updates by Darryl Baylis, Megha Bambra, and Eunice Obugyei.

AndroidRW

Clearly there’s a demand for Android app development since there are over two billion monthly active users around the globe. To say that it’s an exciting platform and space to make apps for is an understatement.

Beginning Android Development

There aren’t any prerequisites for this tutorial, other than a willing mind and a Mac — you can certainly develop for Android on PC, but these instructions are tooled for Mac-based developers. The instructions are similar but slightly different on Windows and Linux.

You’ll learn how to set up all the tools needed to start you on your way to becoming an Android developer. Here’s what you’ll do in this beginning Android development tutorial:

  1. Download and install Android Studio 3.0.
  2. Set up testing for your app on devices and emulators.
  3. Create a simple “Hello World!” Android app that displays text on your device’s or emulator’s screen.
  4. Import a sample project into Android Studio.

Installing Android Studio

One of the most important parts of getting started with any new platform is setting up your environment, and this is no different with Android.

It’s important to take your time and follow each step methodically. Even if you follow the steps perfectly, you may have to troubleshoot a small issue or a few. Your system configuration or product versions can make for unexpected results.

Installing Java

With all of this in mind, let’s quickly check that you have the Java Development Kit (JDK) installed. Even if you’re planning on doing all of your Android development in Kotlin, you’ll still need Java installed on your development machine. To check, you’ll use trusty old Terminal.

Note: You’ll learn the essential steps for this tutorial in the next few paragraphs, but if you’d like to deepen your knowledge of the Terminal, you’ll find a good introductory tutorial about it in this post from Django Girls.

The Terminal

In a nutshell, using Terminal is kind of like looking under your car’s hood. It’s how you really get to know the machine face-to-face, without any complex graphical interface to interfere.

You can find the Terminal app quite easily on a Mac: open Spotlight by hitting command+spacebar and type terminal into the search at the top of the screen and select Terminal when it shows up.

Spotlight

Once you have Terminal open, type in java -version. You should see some output that mentions a version number, like below.

java version

If that’s not what you see, then you don’t have the JDK installed. Terminal might tell you -bash: java: command not found, or it could say No Java runtime present, requesting install. and trigger a pop up that will lead you down the yellow brick road…to Oracle’s website.

Beginning Android development - Install Java

You can either click More Info… or head over to Oracle to download the JDK from Oracle.

Install the JDK if needed, and once you’re done, head over to the Android Studio page and click the Download Android Studio button.

Android developer site

Getting Android Studio

Google constantly updates this page, so the version you see may very well be newer than the screenshot above. Once you click the Download Android Studio button, you’ll see a request to agree to the terms and conditions.

android-studio-terms-conditions

After reading these carefully (everybody takes the time to fully read these, right?) accept and click the blue button underneath titled Download Android Studio For Mac. Once the download is complete, you can install Android Studio just like how you install any other program.

The download link will redirect to a page that contains installation instructions for macOS, Windows or Linux. If the instructions don’t appear, then you can view them here.

Once installation wraps itself up, go ahead and launch Android Studio!

Android Studio banner

Setting up Android Studio

The setup wizard will greet you the first time it loads.

Setup Wizard

Click Next to move to the Install Type screen. This whole process will probably take several minutes.

Screen Shot 2015-11-08 at 8.09.21 PM

Check the box for Standard and click Next. You’re presented with a choice of UI Theme:

UI Theme Selection

Pick a theme and click Next. On the Verify Settings window, you’ll have an opportunity to confirm your setup:

Verify Settings

Click Finish to start downloading the SDK components.

component installation

While downloading, you will likely be prompted for your admin password, in order to install HAXM, a tool from Intel that will greatly speed up Android Virtual Devices aka AVDs:

HAXM installation prompt

When the download is complete, click Finish.

installation complete

Android Studio Welcome Screen

After a few minutes, you’ll have the welcome screen, which serves as your gateway to building all things Android.

welcome screen

Even though you just downloaded Android Studio, it’s possible that it’s not the latest version. Select Configure/Check for Update at the bottom of the welcome screen to check whether any updates are available.

check for updates

If an update is available, a window like the screenshot below will appear. Click the Update and Restart button and let it do its thing.

update screen

The Android SDK Manager

Each version of Android has its own SDK (Software Development Kit) that enables you to create applications for the Android platform. Since you just went through the setup wizard, you’ll already have the latest version of the SDK available to you.

Installing a New SDK

It’s useful to know how to install additional versions of the SDK to help you develop for all supported versions of Android.

SDKs allow you to create Android Virtual Devices (AVDs) according to your personal configuration for the purpose of testing your app.

From the Android Studio welcome screen, select Configure/SDK Manager.

configure sdk manager

Once it launches, you’ll see a window like the one below:

Android Studio - SDK Platforms

SDK Platforms

The first tab of this window, SDK Platforms, lists the Android SDK platforms available for download.

Enabling the Show Package Details option displays the individual SDK components, such as the platform itself and the sources pertaining to the API level like system image.

sdk platforms with details

Take note of the checkbox next to the SDK platform; it will be pre-selected if an update is available.

By default, the SDK Manager installs the latest packages and tools. Select the SDKs as shown in the screenshot above. If you wish to install other SDKs, just select them for installation.

SDK Tools

The SDK Tools tab lists developer tools and documentation along with the latest versions. Similar to the first tab, checking Show Package Details will display available versions of the SDK tools.

Three of the selected components in this list, for example, are Android SDK Build-Tools, Android SDK Tools and Android SDK Platform-Tools. Each contains components that are designed to assist in the development of Android and work across multiple SDKs. Go with the default selection on this tab.

sdk tools

SDK Update Sites

The SDK Update Sites tab displays the update sites for Android SDK tools and add-ons. You’re not limited to what’s listed under that tab. You can add other sites that host their own Android SDK add-ons, and then download them from those sites.

sdk update sites

For the purpose of setting up correctly, select the options that are checked in the screenshot above. Click Apply at the bottom if it’s active. You’ll see a confirmation dialog for the chosen packages; accept and continue. Click OK to close the window.

The confirmation dialog will disappear and a license agreement will popup.

Android Studio license agreement

Read through it, select the Accept checkbox and click Next. The SDK Manager will download and install the selected items. Once it’s done, click Finish. You’ll be directed back to the SDK Manager window where clicking OK will take you back to the Welcome to Android Studio screen.

This is where the fun begins!

Creating Your First Project

Android Studio has a nice little step-by-step tool to help you create your project. Click Start a new Android Studio Project from the Welcome to Android Studio screen:

 Start new project

Note: If you currently have an Android Studio project open and can’t see the welcome screen, select File\New Project from the menu to create a new project.

Identify Your Project

Android Studio will present you with a project creation screen:

configure project

Enter OMG Android in Application name as shown above. Feel free to put your own name in the Company domain text field. As you type, you’ll notice the Package name automatically changes to create a reverse domain style name per your entries.

The Package name is used to uniquely identify your app so that any work done on a device is always properly attributed to the source, thus preventing confusion between apps.

You can set the Project location to any location on your hard drive — keep the default if you don’t have a preference.

You should check the Include Kotlin support checkbox if you’re building a project using Kotlin. This will configure Kotlin in your project, and all template source files will be created in Kotlin.

Click Next at the bottom of the window.

Choose an SDK

The next screen is the Target Android Devices window. This is where you select device types and operating systems to target.

The Minimum SDK drop-down menu sets the minimum version of Android requires to run your app. The newer the SDK, the more features you’ll have at your disposal; however, newer SDKs support fewer devices.

Selecting this value is simply a matter of balancing the capabilities you want and the devices you want to support. This is where developing for Android can get a little tricky.

If you really want to get into the details of what Minimum SDK version is best for your App, let Android Studio help you out.

As you change the Minimum SDK in the drop down menu, the percentage in the text underneath reflects what percentage of devices currently run that version of Android.

Click Help me choose underneath the drop down list to learn more about each SDK’s set of features.

API Version Distribution

For more on API versions statistics, check out the Android Dashboards, which are updated periodically.

For now, you just want an App that works on an Android Phone, and that is what you’ll see by default, alongside the default Minimum SDK. For this project, select SDK of API 16: Android 4.1 (Jelly Bean) and click Next.

target android devices

Set the Default Activity

The next step is to select your default Activity.

Beginning Android development - Add activity

Think of an Activity as a window within your app that displays content with which the user can interact. An Activity can take up the entire screen or it could be a simple pop-up.

Your options on this particular template range from a Basic Activity, which is a blank screen with an Action Bar and a Floating Button right up to an Activity with an embedded MapView.

You’ll make a lot of activities as you develop more apps, so get to know them and know them well.

Select the Basic Activity and click Next.

Configure Activity

To speed this part up a little bit you’ll use the pre-populated default values, but what is actually done with these values?

  • Activity Name: This gives your Activity a name to refer to in code. A .kt file will be created and will use the contents of this text field to give the Activity subclass a name, which will ultimately be the name you use to refer to this Activity in your code.
  • Layout Name: You’re going to define your Activity in Kotlin, but the layout it shows to the user is defined in a special sort of Android XML. You’ll learn how to read and edit those files shortly.

Click Finish.

Building the Project

Android Studio takes this as a cue to go do a bunch of behind-the-scenes operations and create your project. As it shoots out descriptions of what it’s doing, you may notice it says something like this:

project building

Here, you see your project name, which is familiar. But then there is this Gradle word as well.

The benefit of having a modern IDE like Android Studio is that it handles a lot for you. But, as you’re learning how to use the software, it’s good to have a general sense of what it does for you.

Gradle

Gradle is a build tool that’s easy to use, and if you investigate further, you’ll find it contains advanced options. It takes your Java or Kotlin code, XML layouts and the latest Android build tools to create the app package file, also known as an APK (Android Package Kit) file.

You can customize your configurations to have development or production versions of the app that behave differently. You can also add dependencies for third-party libraries.

After a brief moment, Android Studio will finish building your project. The project is pretty empty, of course, but it has everything it needs set up so that it can be launched on an Android device or emulator.

You’ll likely see a “Tip of the Day” presented by Android Studio:

Tip of the Day

Depending on what version of the build tools you have installed, you may also see a build error in the Messages pane:

Messages pane

If so, just click the Install Build Tools X.Y.Z and sync project link. Android Studio will then re-build the project, and you’ll be at the Project screen:

android studio screen

Let’s take a brief look at the different parts of the project.

  • The manifests/AndroidManifest.xml file provides to the Android system important information required to run your app.
  • The res directory is your resource directory. Application resources such as images, XML layouts, styles, colors etc. are defined in this directory.
  • The res/layout directory is where all your UI (User Interface) will be designed. You will use Android XML to design your UI.
  • The res/menu directory is where you define the contents of your application’s menus.
  • The res/values directory is where you define the resources such as dimensions (res/values/dimens.xml), colors (res/values/colors.xml), strings (res/values/strings.xml), etc.

Open res/layout/activity_main.xml and click Text at the bottom of the screen.

This shows you the xml code for your main layout. It also shows a preview of how it will look like on a device on the right side of the screen.

Note: If the Preview screen is not shown by default for you, open it by selecting View\Tool Windows\Preview from the menu

tool windows preview

Running on an Emulator

You’ve got Android Studio and you’ve created an app. So how do you run it?

Android Studio comes with the ability to set up a software-based Android device on your computer and run apps on it, browse websites, debug and everything you would expect from a simulator. This capability is known as the Android Emulator.

You can set up multiple emulators and set the screen size and platform version for each to whatever you like. Good thing, too. You’d need a whole room dedicated to storing devices for testing because there are so many out there — okay, maybe that’s an exaggeration, but you get the idea. :]

If you ran through the setup wizard earlier using the standard installation, then you’ll already have an emulator set up and ready for you.

Up until recently, your computer would have to emulate everything an Android device would try to do, right down to its hardware, which runs an ARM-based processor. Most computers make use of x86-based processors, meaning your computer has to translate each instruction to one that an ARM-based processor would understand and this takes a significant amount of time. To reduce this overhead, Android Studio has recently adopted the HAXM driver which is able to speed things up a bit.

You still have the option to create an emulator that is as close to an actual device as you can, but be aware that the initial load times can drag a bit and have put off many an Android developer from using emulators at all.

With all that being said…let’s set up an emulator anyway, because you do need to know how!

Creating an Emulator

Click the AVD Manager. It’s a button near the right side of the toolbar that shows an Android popping its head up next to a device with a purple display:

avd manager

The AVD Manager will open to a screen with an option to create a new device:

avd manager 2

Virtual Device

Click the Create Virtual Device… button to start the process of creating a new virtual device.

The first step is to select the type of device. The Category section, on the left side of the screen, shows a list of the different device types you can emulate (TV, Wear, Phone, Tablet). Make sure the Phone option is selected. In the middle of the screen, there is a list of specific devices with their screen size, resolution and density. Take a moment to explore them.

select hardware

What you need now is just to emulate a phone-sized device, but if you wanted to emulate an Android Wear watch or an Android TV then you have options to do so here.

Select Pixel 2 in the list of devices available to you from the phone category and click Next.

Select Android Version

On the next screen, you have to select the version of Android the virtual device will run.

For this tutorial, select Oreo and make sure the one selected has the value x86 in the ABI column so the emulator runs as fast as possible on your x86 computer.

System Image

Note: If that version is not already downloaded, click on the Download link beside the release name to download before you continue.

Click Next once you’re done to advance to the final screen.

Verify Virtual Device

The last screen lets you confirm your choices and gives options to configure some other properties such as device name and startup orientation. Clicking the Show Advanced Settings button, shows you extra configurations you can change such as Camera, Network and Memory settings.

Verify Pixel 2

Use the defaults and click Finish.

verify configuration pixel

avd list

Close the AVD Manager to go back to Android Studio’s main view. Now that you’ve configured everything, click the Run button.

run app

Selecting a Device

A new window will appear, asking you to choose the device you wish to test your App on. You currently have no devices running, so select the Pixel 2 you just created and click OK.

select deployment target

Note: If you get an error that says This AVD’s configuration is missing a kernel file!!, check to make sure that you don’t have the ANDROID_SDK_ROOT environment variable set from a previous installation of the Android SDK. See this thread on Stack Overflow for more troubleshooting tips.

In the event that it doesn’t work the first time or takes several minutes for the emulator to fire up correctly, don’t worry, that’s not entirely unexpected. Stick with it. Once it’s ready, you should see something like this:

mobile ap

Whoa. You just made your first Android app.

The Emulator Toolbar

As you may have noticed, there’s a panel on the right side of the emulator. That is the emulator toolbar. The toolbar lets you perform various tasks such as taking screenshots, screen rotation, and volume control and also to perform extended functions such as simulating device location, phone calls, message sending, finger print, etc.

To access the extended functionalities, click the More () icon at the bottom of the toolbar.

extended controls

Running on a Device

android dev options

If you have an Android device you want to run your app on, follow the animated GIF on the right. It demonstrates how to enable developer mode on your device.

Here are the step-by-step instructions to enable Developer Mode on an Android device:

  1. Go to Settings on your device.
  2. Scroll all the way down and select About phone.
  3. Scroll to Build number and tap in multiple times. You’ll see a toast come up that states “You’re n steps away from becoming a developer”. Keep tapping and it will change to “You’re now a developer!” once it’s enabled.
  4. Go back to Settings screen and scroll all the way to the bottom. You’ll now see Developer Options enabled.
  5. Select Developer Options. Next, turn on the USB debugging switch under the Debugging section.
  6. Connect your device to your computer via USB.
  7. Your phone will prompt you to confirm this option via a dialog that states Allow USB debugging? — click OK.
  8. Next, the phone will ask you to register your computer’s RSA key fingerprint. If this is a trusted machine, then check the Always allow from this computer option.

Now that you’ve configured your device, click the Run button.

run app

Just like before, you’ll get a prompt from the Select Deployment Target dialog. The device should now appear in this dialog. Select it and click OK.

Ahh…isn’t it rewarding to see the app on your device? Go ahead and show it off to your friends. :]

Note: If the app is already running, you might not get the prompt. This is because of a new functionality in Android Studio know as Instant Run. We’ll talk about it in the next section of this tutorial. Close the emulator, go back and click the Run button again.

Instant Run

From version 2.0 of Android Studio, a new functionality was introduced called Instant Run. Instant Run allows you to push updates (code and resources) to a running app on a device or emulator without performing a full reinstall. By doing this, you are able to view your changes in a shorter time.

There are three kinds of changes you can make to your code: a hot swap, warm swap, or cold swap. Instant Run pushes updates by performing one of the following, depending on the kind of change you made:

  1. Hot Swap: This applies to method changes. Your app continues to run but uses a stub method with the changes performed the next time the relevant method is called. This is the fastest swap.
  2. Warm Swap: This swap applies to resource changes. With this, your the current activity will restart to update the changed resources.
  3. Cold Swap: With this, Instant run restarts the whole app even though it does not perform a re-install. This swap applies to structural code changes

Testing Instant Run

Go ahead and try out Instant Run.

To enable Instant Run, select Android Studio \ Preferences \ Build, Execution, Deployment \ Instant Run. Ensure that Enable Instant Run to hot swap code/resource changes on deploy is checked and that Restart activity on code changes is unchecked.

Instant Run

If your app is not yet running, launch it by clicking the Run button, and wait for it to launch.

When the app is running, the Apply Changes button on the right side of the Run becomes enabled.

Apply Changes

As your app is now running, clicking on the floating button, shows the message, Replace with your own action at the bottom of the screen.

Change that message to test out Instant Run.

Open MainActivity, in the onCreate() method, replace the text: Replace with your own action with Hello Instant Run.

Then click the Apply Changes. Now when you click the button, you will see the new message. This is an example of a hot swap.

Instant Run helps you code faster by significantly reducing the time it takes to update your app with code and resource changes.

Importing an Existing Project

During your Android app-making journey, you’ll find times where you need to import existing projects. The steps below will guide you through how to import a project:

  1. Download this project to use as your test subject.
  2. Once downloaded, unzip the contents and place them somewhere easy to get to.
  3. In Android Studio, go to File/New/Import Project….
  4. An open sheet will appear. Select the unzipped project from Step 1 and click Open.
  5. Import Project

  6. You’ll now see all the necessary files of the imported project in the project explorer.

Project Explorer

It’s build and run time! Click the Run button in the toolbar and select either the emulator or device you’ve already set up.

CardView Sample

Where To Go From Here?

You’ve covered a lot of ground in this beginning Android development tutorial: from downloading and installing Android Studio, through creating your first “Hello World!” app, to deploying it on a physical device!

Keep reading our other Android tutorials, which we’re continually updating to Kotlin and recent versions of Android Studio.

In the meantime, you can follow Android — like any language or framework, Android’s development community is a strong asset and supplier of endless reference. It’s never too soon or too late to start checking out Google’s I/O conference, Android Developers blog or Android Developer videos.

The Android robot is reproduced or modified from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.

I hope you enjoyed this Beginning Android Development tutorial — you’ve successfully installed Android Studio and are now ready to take on the world of Android development. If you have any questions or comments, please join the discussion in the comments below.

The post Beginning Android Development with Kotlin, Part One: Installing Android Studio appeared first on Ray Wenderlich.


Viewing all articles
Browse latest Browse all 4370

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>