Android SDK Versions Tutorial With Kotlin

New SDK versions released with each new version of Android provide great new features. In this tutorial we will learn how to utilize them in our apps. By Kevin D Moore.

Leave a rating/review
Download materials
Save for later
Share
Update Note: Kevin Moore updated this tutorial. The original tutorial was
written by Eunice Obugyei and Eric Crawford, who updated it to Kotlin.

Ever since the first release of Android, the range of supported devices has grown to represent a wide array of phones, smart watches, cars, Android Internet of Things and more. Everything necessary to start developing Android apps for those devices falls under one specification called the Android SDK (software development kit). New SDK versions are released with each new version of Android, and that is the focus of this tutorial.

These new SDK versions take advantage of the increased processing power available on the latest devices to provide great new features. Awesome, right? The flip side, of course, is that Android developers face the challenge of making sure an app will work on a range of devices running different versions of the Android SDK.

There are some best practice guidelines and tools to help get the work done without compromising your UX or deadlines.

Note: This Android SDK Versions tutorial assumes you are already familiar with the basics of Android development and Kotlin. If you are completely new to Android development, read Beginning Android Development and our other Android and Kotlin tutorials to familiarize yourself with the basics.

In this Android SDK Versions tutorial, you’ll learn about:

  • Android SDK versions and API Levels
  • Android Support Libraries and their importance
  • How to use the Android Support Library to make an app backward-compatible
  • How to use the CardView Support Library

To put theory into practice, you’ll play with a simple app called Continents. Continents gives short descriptions for all of the continents in the world.

Note: This tutorial requires Android Studio 3.3.2 or later.

Getting Started

Click on the Download Materials button at the top or bottom of this tutorial to get your hands on the starter project for this tutorial and extract the downloaded .zip file to get the project.

Select Open an existing Android Studio project from the Quick Start menu to open the starter project:

If you are on a windows machine you can also select File ▸ Open. Navigate to and select the starter project folder.

Emulating Different SDK Versions

We want to try running the sample app on different Android versions. But it’s unlikely anyone has an Android device for every single API Level of the SDK. So first, let’s learn how to set up emulators with different SDK versions.

To set up an emulator, locate the AVD (Android Virtual Device) Manager on the Android Studio Toolbar.

Creating a Virtual Device

If the Toolbar is not showing, select View ▸ Toolbar to show it. You can also select select Tools ▸ Android ▸ AVD Manager to open the AVD Manager.

Click the Create a virtual device button. That will open the Select Hardware section of the Virtual Device Configuration window.

Select a device of your choice and click Next. That opens the System Image section, which currently shows recommended system images.

The x86 Images tab will list all the x86 emulator images. The Other Images tab will show both ARM and x86 emulator images.

Note: It is recommended to always use x86 images. These will run the fastest on most PC and Mac computers

Downloading a System Image

To download a system image that you do not already have installed, click the Download link by the release name.

Notice that the Android platform currently has twenty five major versions of the SDK. Starting with Android 1.5, major versions of the SDK have been developed under a confectionery-themed code name. Google has managed to choose these code names in an alphabetical order. They haven’t run out of names of sweets yet. :]

Each version (minor or major) of the Android SDK has an integer value that uniquely identifies it. This unique identifier is referred to as the API Level. The higher the API Level, the later the version. For developers, API Level is important because it is what determines the range of devices an app can run on.

Look at an example, the Android 9.0 release. You can see that:

  • It is the most recent version of the Android SDK
  • Its version number is 9.0
  • Its code name is Pie
  • It has an API Level of 28

For this tutorial, you will need at least two emulators, one with API Level 16 and another one with API Level 28.

Going back to the System Image screen in Android Studio, click the Download button for each of the SDK versions you will need for this tutorial that you have not already downloaded (Level 16 and Level 28). Then select the system image for Level 28 and click Next.

On the next screen, click Finish.

Repeat the same steps to set up an emulator with API level 16.

Running the Sample App

Try running the sample app on the emulator running API Level 28:

It all looks great, right? But if you were to try and run the app on a device with API Level lower than 28 it wouldn’t run. This is because the app only runs on devices that run Android API Level 28 and upwards, which isn’t great for older devices. Later, you’ll learn how to extend the app’s support from Android API Level 28 to as low as Android API Level 16.

SDK Versions and API Levels

As mentioned earlier, the API Level is a unique integer that identifies a specific version of the Android SDK. Take a look at how to specify API Levels in Android Studio to compile and release an app.

Open build.gradle for the app module:

Here, you can see three important attributes:

  • minSdkVersion is the minimum API Level with which the app is compatible. The Android system will prevent a user from installing the app if the system’s API Level is lower than the value specified in this attribute. Android requires the minSdkVersion attribute to always be set.
  • targetSdkVersion is the API Level that the app targets. This attribute informs the system that you have tested against the target version. The targetSdkVersion defaults to the minSdkVersion if not specified.
  • compileSdkVersion specifies the API Level to compile the app against.

These attributes can be adjusted in the app modules build.gradle file.

Note on SDK previews: It’s important to know that when you set the compileSdkVersion to a preview release of the Android framework, Android Studio will force the minSdkVersion and targetSdkVersion to equal the exact same string as compileSdkVersion. This policy is necessary to prevent situations wherein you might upload your app to the Google Play Store. As a result, you can only run apps where compileSdkVersion is set to a preview release on emulators with that exact same preview and you won’t be able to run it on older devices.

Backward Compatibility

The Android SDK is by default forward compatible but not backward compatible — this means that an app that is built with and supports a minimum SDK version of 3.0 can be installed on any device running Android versions 3.0 and upwards — but not on devices running Android versions below 3.0.

Since the Android SDK is not backward compatible, you should choose the minimum SDK carefully. This means striking a balance between supporting a wide range of devices and designing an app that implements useful features in later SDK versions.

For example, when Android 3.0 was released in 2011, the Action Bar was unleashed on the Android Community. Since the Action Bar was only supported in Android 3.0 and later, using it in an app meant choosing either a cool user interface or supporting devices that ran older versions of the SDK. Sometimes you can’t have your honeycomb and eat it, too. :[

Or can you? To help with the Action Bar issue, the Android Support Library introduced a backward-compatible version in the v7-appcompat Support Library. So it would allow developers to support older versions of the SDK and still use the latest Action Bar APIs in their apps. Sweet! Honeycomb for everyone!

Take a deeper look at what the Support Library does and how it works.

Note on picking minimum sdk version: Google provides a Dashboard that breaks down the user distribution percentage per api level. You can use this to help target a good percentage of users. There is also information provided when you create your project and pick your minimum API level that shows what percentage of devices your app will run on.

Android Support Libraries

A wide range of components make up what is referred to as the “Support Library” or “Support Libraries,” and they can be categorized in two groups:

  • The AppCompat library: The intention here is to make sure all (or most) of the framework APIs for the latest API Level have been backported to earlier versions and can be found in this single library. The first version of AppCompat was released at Google I/O 2013.

    The goal of this first release was to allow developers to backport the ActionBar to devices running Ice Cream Sandwich level. This gave API parity to the framework across as many API Levels as possible. Since then, the AppCompat library has continued to evolve. And with Android Lollipop, the Support Library is now at the point where the API is equivalent to the framework itself — the first time that has ever happened. :]

  • Others: The rest of the libraries that make up the Support Library essentially provide new functionality with the same consideration for backward compatibility (palette, gridview, gridlayout, recycler view, material design widgets).

When you break these up into independent libraries, you can pick and choose the ones you need in your project. It’s important to note that each support library is backward-compatible to a specific API Level. And they are usually named based on which API Level they are backward-compatible to. For example, v7-appcompat provides backward compatibility to API Level 7.

You can find the full list of components that fall under the Support Library in the Android documentation.

Note: Support Library minimum SDK change: Beginning with Support Library release 26.0.0, Google has changed the minimum supported level to Api 14. This means that your minimum sdk version cannot be set below Api level 14 when using version 26.0.0+ of the Support Library.

AndroidX Support Libraries

Google has decided to reorganize their support libraries and has named them AndroidX or Jetpack. We will not be going into detail about these libraries as they are not all out of alpha stage. A future version of this tutorial will discuss them. You can find more information at: AndroidX Support Libraries

Using an Android Support Library

Time to see an Android Support Library in action! Open MainActivity.kt. As you may have noticed in the onCreate() method, the app uses a Toolbar (which is part of the material design patterns) instead of an Action Bar.

The Toolbar was added in API 21 (Android Lollipop) as a flexible widget that can be used anywhere in layouts, be animated and change it’s size, unlike the Action Bar.

Thanks to AppCompat, that feature has been back-ported all the way to API 14, which is code-named Ice Cream Sandwich (are you hungry yet?). You’re going to use the v7-appcompat Support Library to extend your app’s compatibility to a minSdkVersion of 16.

Update Build File

First, add google() to the Maven repositories in your project-level build.gradle file, if it’s not already there:

repositories {
    jcenter()
    google()
}

Now, open build.gradle for the app module and add the following to the dependencies section:

implementation "com.android.support:appcompat-v7:28.0.0"

By adding this, you’re declaring the appcompat-v7 Support Library as a dependency for your app. You can ignore the warning to use a newer version of the Support library. Though you may update, it’s recommended you stick to the one in this tutorial.

Next, change the minSdkVersion attribute to 16.

minSdkVersion 16

Here, you’re declaring that the app should be able to run on devices with Android SDK version 4.1.2. Now try running your app on an emulator running API Level 16. You should see the following exceptions in the logcat:

The important line to look for is:

Caused by: java.lang.ClassNotFoundException: android.widget.Toolbar

The ClassNotFoundException error indicates that there is no such class in the SDK version you’re running the app against. Indeed, it’s only available in API Level 21, while you’re currently running API Level 16.

Updating for Backward Compatibility

You’re going to update the code to use the backward-compatible version of Toolbar. Open MainActivity.kt, and update the android.widget.Toolbar import statement to match the following:

import android.support.v7.widget.Toolbar

This replaces the SDK import with one from the AppCompat library.

Next import the AppCompatActivity from the AppCompat library:

import android.support.v7.app.AppCompatActivity

Next update the MainActivity class definition line so that it inherits from AppCompatActivity:

class MainActivity : AppCompatActivity(), ContinentSelectedListener

Once again, you’re replacing a class from the latest SDKs with one that exists in the Support Library.

You now need to work through the class and replace some method calls with their Support Library equivalents:

  • Find the call to setActionBar(toolbar) at the end of the onCreate() method body and update it to setSupportActionBar(toolbar).
  • Find the calls to actionBar? in onContinentSelected(), goToContinentList(), and onBackPressed() and replace both of them with supportActionBar?.
  • Replace the calls to fragmentManager() in onContinentSelected() and goToContinentList() with supportFragmentManager().
  • Change the code in goToContinentList() to fix the error in replacing the fragment:
    val fragment = MainFragment.newInstance(continentNames)
    supportFragmentManager
        .beginTransaction()
        .replace(R.id.frameLayout, fragment)
        .commit()
    mainFragment = fragment

Updating Fragment Classes

Open DescriptionFragment.kt and MainFragment.kt, find the following line:

import android.app.Fragment

And update to match the following:

import android.support.v4.app.Fragment

Here, you’re using the support version of the Fragment class instead of the one in the main SDK. The latter can only be used in apps with a minSdkVersion of 14 and above.

Note: AppCompat v7 depends on the v4 Support Library. That’s why you can also use all the APIs in the android.support.v4.app package.

So far, you’ve replaced all the main API calls with corresponding methods from the Support Library. Next you will need to update your layout files to use the Support Library.

In the res / layout folder, open toolbar_custom.xml and do the following:

  • Change android.widget.Toolbar to android.support.v7.widget.Toolbar
  • Change ?android:attr/actionBarSize to ?attr/actionBarSize

Again, all this does is change the package name from android to v7-appcompat.

Now that all of the compile-time errors have been checked and fixed, try to run the app again. You will now get the following run-time error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.raywenderlich.continents/com.raywenderlich.continents.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

Updating Styles

The error message is pretty self-explanatory, but why do you need to use the AppCompat theme? A feature from the Lollipop release of AppCompat is the different approach to theming. One of the interesting things about this is the capability to get an L-friendly version of your app on prior versions. If an app uses the framework version of everything (Activity instead of AppCompatActivity for example), it would only get the material theme on phones with the L release. Devices with prior releases would get the default theme for those releases. The goal of the AppCompat theming feature is to have a consistent experience across all devices.

In the res\values folder, open styles.xml, and change android:Theme.Black.NoTitleBar to Theme.AppCompat.NoActionBar.

Now, build and run. You can test the app on an API 16 device or emulator as well.

Well done! The sample app is now backward compatible. Ice cream sandwich, lollipops and jelly beans for everyone!

Now, throw in some cards to make the detail screen look nicer.

Using the CardView Support Library

Open build.gradle for the app module and add the following to the dependencies section:

implementation "com.android.support:cardview-v7:28.0.0"

Now, sync your project. Adding this declares the v7-cardview Support Library as a dependency for the app.

Open the fragment_description.xml file and place the ImageView in a CardView:

<android.support.v7.widget.CardView
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_gravity="center"
    android:layout_weight="1"
    card_view:cardBackgroundColor="#316130"
    card_view:cardElevation="20dp">
    <ImageView
      android:id="@+id/continentImage"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:contentDescription="@string/continent_image_description"
      android:paddingBottom="@dimen/activity_vertical_margin"
      android:src="@drawable/africa" />
</android.support.v7.widget.CardView>

Notice that when using widgets from the Support Library, some XML attributes (cardBackgroundColor and cardElevation for the CardView) are not prefixed with “android.” That’s because they come from the Support Library API as opposed to the Android framework. Press Option-Return (or Alt-Enter on PC) if you need to set up the card_view namespace in the .xml file.

Now, build and run the project:

Cool, you’ve added this new-style CardView to your app and using the compatibility library it works from modern versions of Android, right back to ancient API-level 16.

Did You Say Material Design?

You’ve successfully used the AppCompat theming to give the app the Android Lollipop look and feel across a wide range of SDK versions. In addition to these elements, the Material Design specification includes many more patterns and widgets not contained in AppCompat. This is where the Design Library comes into play. It provides widgets such as navigation drawers, floating action buttons, snackbars and tabs. Let’s include it in the project and add a floating action button.

In build.gradle, add the following in the dependencies section:

implementation "com.android.support:design:28.0.0"

Next, add the following XML element above the closing tag for FrameLayout in fragment_description.xml:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/search_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="16dp"
    android:src="@drawable/ic_search_white_18dp" />

Build and run. You will see the floating button as expected.

fab-button

Where to Go From Here?

Congratulations! Finally, you’ve learned about Android SDK versions and their sweet code names. You made an API Level 28 app, backward-compatible to API Level 16, and used the CardView and design library to add additional components. You might also have a sugar craving. :]

Blame Android.

Blame Android.

The final project for this Android SDK Versions tutorial can be downloaded by clicking on the Download Materials button at the top or bottom of this tutorial.

If you are interested in the Android SDK version history, check out this wikipedia page or the versions page on the Android developer site. You can also read further about the minSdkVersion and targetSdkVersion attributes from the manifest page on the developer site. Finally, check out the developer pages on Support libraries and its feature list.

We hope you enjoyed this Android SDK Versions tutorial, and if you have any questions or comments, please join the forum discussion below!