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

Android SDK Versions Tutorial with Kotlin

$
0
0
Update Note: This tutorial has been updated to Kotlin by Eric Crawford. The original tutorial was
written by Eunice Obugyei.

Android sdk versions

Ever since the first release of Android, the range of supported devices has grown to represent a wide array of phones, smart watches and more. Everything necessary to start developing Android
applications 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 our focus for 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 application will work on a range of devices running different versions of the Android SDK.

Luckily, there are some best practice guidelines and tools to help get the work done without compromising on UX or deadlines.

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 application called Continents. Continents gives short descriptions of the continents in the world.

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.
Note: This tutorial requires Android Studio 3.0 Beta 4 or later.

Getting Started

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

If you are prompted to install (or update to) a new version of the Android build tools, or are prompted to update your Gradle plugin version, please do so.

Build and run the project on the emulator or device to make sure it compiles and runs correctly.

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

Let’s look at an example, the Android 8.0 release. We can see that:

  • It is the most recent version of the Android SDK
  • Its version number is 8.0
  • Its code name is Oreo
  • It has an API Level of 26

For this tutorial, we will need at least two emulators, one with API Level 15 and another one with API Level 26.

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 15 and Level 26). Then select the system image for Level 26 and click Next.

On the next screen, click Finish.

Repeat the same steps to setup an emulator with API level 15. You may choose one with API level 16 instead if you are unable to download one with API level 15.

First Run

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

First Run

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

SDK Versions and API Levels

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

Open build.gradle for the app module:

build.gradle

Here we 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 application 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 application 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 application 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 where you might upload your app to the Google Play Store. As a result, you can only run applications 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 application 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!

Let’s 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.

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 IceScreamSandwich 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 L 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.

How to Use 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 in 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 15.

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:26.0.1"

By adding this, you’re declaring the appcompat-v7 support library as a dependency for your application. 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 15.

minSdkVersion 15

Here you’re declaring that the app should be able to run on devices with Android SDK version 4.0.4. Now try running your application on an emulator running API Level 15. 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 15.

Update For Backward Compatibility

You’re going to update the code to use the backward-compatible version of Toolbar. In 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().

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

Update 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 15 device or emulator as well.

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

Let’s throw in some cards to make the detail screen look nicer.

How to Use the Card View Support Library

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

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

Adding this declares the v7-cardview support library as a dependency for the application.

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. Hit option+return (or Alt+Enter on PC) if you need to setup 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 15.

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:26.0.1"

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

Backport All the Things?

Some features in the latest releases of the SDK are just too complex to backport. Ultimately, it’s your call to strike the right balance between performance and usability. If you find yourself wanting to use an unavailable framework API, you can check for the API Level at run-time.

For the following snippet from MainActivity, import the classes from the base package instead of the Support Library package. Then in the onContinentSelected, add the following after the description fragment is instantiated but before the fragment transaction:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  descriptionFragment.enterTransition = Fade()
  mainFragment?.exitTransition = Fade()
  descriptionFragment.exitTransition = Slide(Gravity.BOTTOM)
  mainFragment?.reenterTransition = Fade()
  descriptionFragment.allowReturnTransitionOverlap = true
}

Build and run on both emulators. You should see no animations on the emulator running API Level 15, but notice the fade in and slide out on the emulators running API Level 25 and above:

side-by-side

Where To Go From Here?

Congratulations! Finally you’ve learned about Android SDK versions and their sweet code names. You made an API Level 26 application backward-compatible to API Level 15, 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 here.

If you are interested in 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!

The post Android SDK Versions Tutorial with Kotlin 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>