Home Mobile Learning Android Application Development

Learning Android Application Development

By Raimon Ràfols Montane , Laurence Dawson
books-svg-icon Book
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book
The mobile app market is huge. But where do you start? And how you can deliver something that takes Google Play by storm? This guide is the perfect route into Android app development – while it’s easy for new apps to sink without a trace, we’ll give you the best chance of success with practical and actionable guidance that will unlock your creativity and help you put the principles of Android development into practice. From the fundamentals and getting your project started to publishing your app to a huge market of potential customers, follow this guide to become a confident, creative and reliable mobile developer. Get to grips with new components in Android 7 such as RecyclerView, and find out how to take advantage of automated testing, and, of course, much, much more. What are you waiting for? There’s never been a better time – or a better way – to get into Android app development.
Publication date:
August 2016
Publisher
Packt
Pages
320
ISBN
9781785286117

 

Chapter 1. Getting Started with Android Development

In this chapter, we will go through all the steps required to start developing Android devices. We have to be aware that Android is an evolving platform and so are its development tools. We will show how to download and install Android Studio and how to create a new project and run it on either an emulator or a real device. We will spend some time going through some additional components that we will use in later chapters.

  • Installing Android Studio

  • Creating a sample project

  • Additional components

 

Setting up Android Studio


Before being able to build an Android application, we have to download and install Android Studio on our computer. It is still possible to download and use Eclipse with the Android Development Tools (ADT) plugin, but Google no longer supports it and they recommend that we migrate to Android Studio. In order to be aligned with this, we will only focus on Android Studio in this book. For more information on this, visit http://android-developers.blogspot.com.es/2015/06/an-update-on-eclipse-android-developer.html.

Getting the right version of Android Studio

The latest stable version of Android Studio can be found at http://developer.android.com/sdk/index.html.

If you are among the bravest developers, and you are not afraid of bugs, you can always go to the Canary channel and download the latest version. The Canary channel is one of the preview channels available on the Android tools download page (available at http://tools.android.com/download/studio) and contains weekly builds.

The following are other preview channels available at that URL:

  • The Canary channel contains weekly builds. These builds are tested but they might contain some issues. Just use a build from this channel if you need or want to see the latest features.

  • The Dev channel contains selected Canary builds.

  • The Beta channel contains the beta milestones for the next version of Android Studio.

  • The Stable channel contains the most recent stable builds of Android Studio.

The following screenshot illustrates the Android Tools download page:

Note

It is not recommended to use an unstable version for production. To be on the safe side, always use the latest stable version. In this book, we will use the 2.2 preview version. Although it is a beta version at this moment, we will have the main version quite soon.

Installing Android Studio

Android Studio requires JDK 6 or higher: JDK 7 is required as a minimum if you aim to develop for Android 5.0 and higher. You can easily check which version you have installed by running this on your command line:

javac -version

If you don't have any version of the JDK or you have an unsupported version, please install or update your JDK before proceeding to install Android Studio.

Refer to the official documentation for a more comprehensive installation guide and details on all platforms (Windows, Linux, and Mac OSX) at http://developer.android.com/sdk/installing/index.html?pkg=studio.

Once you have JDK installed, unpack the package you have just downloaded from the Internet and proceed with the installation. For example, let's use Mac OSX. If you download the latest stable version, you will get a .dmg file that can be mounted on your filesystem. Once mounted, a new Finder window will appear and will ask us to drag the Android Studio icon to the Applications folder. Just doing this simple step will complete the basic installation.

If you have downloaded a preview version, you will have a ZIP file that once unpacked will contain the Android Studio Application directly (it can be just dragged to the Applications folder using Finder).

For other platforms, refer to the official installation guide provided by Google at the web address mentioned earlier.

First run

Once you have finished installing Android Studio, it is time to run it for the first time. On the first execution (at least if you have downloaded version 2.2), it will let you configure some options and install some SDK components if you choose the custom installation type. Otherwise, both these settings and SDK components can be configured or installed later.

The first option you will be able to choose is the UI theme. We have the default UI theme or the Darcula theme, which basically is a choice of light or dark backgrounds, respectively.

After this step, the next window will show the SDK Components Setup where the installation process will let you choose some components to automatically download and install. On Mac OS, there is a bug in some versions of Android Studio 2.0 that sometimes does not allow selecting any option if the target folder does not exist. If that happens, follow these steps for a quick fix:

  1. Copy the contents of the Android SDK Location field, just the path or something like /Users/<username>/Library/Android/sdk, to the clipboard.

  2. Open the terminal application.

  3. Create the folder manually as mkdir /Users/<username>/Library/Android/sdk.

  4. Go back to Android Studio, press the Previous button, and then the Next button to come back to this screen. Now, you will be able to select the components that you would like to install.

  5. If that still does not work, cancel the installation process, ensuring that you checked the option to rerun the setup on the next installation. Quit Android Studio and rerun it.

 

Creating a sample project


We will introduce some of the most common elements in Android Studio by creating a sample project, building it, and running it on an Android emulator or on a real android device. It is better to display those elements when you need them rather than just enumerate a long list without a real use behind.

Starting a new project

Just press the Start a new Android Studio project button to start a project from scratch. Android Studio will ask you to make some project configuration settings, and you will be able to launch your project. If you have an already existing project and would like to import it to Android Studio, you could do it now as well. Any projects based on Eclipse, Ant, or Gradle build can be easily imported into Android Studio. Projects can be also checked out from Version Control software such as Subversion or Git directly from Android Studio.

When creating a new project, it will ask for the application name and the company domain name, which will be reversed into the application package name.

Once this information is filled in, Android Studio will ask the type of device or form factors your application will target. This includes not only phones and tablets, but also Android Wear, Android TV, Android Auto, or Google Glass. In this example, we will target only phones and tablets and require a minimum SDK API level of 14 (Android 4.0 or Ice Cream Sandwich). By setting the minimum required level to 14, we make sure that the app will run on approximately 96.2% of devices accessing Google Play Store, which is good enough. If we set 23 as the minimum API level (Android 6.0 Marshmallow), our application will only run on Android Marshmallow devices, which is fewer than 1% of active devices on Google Play right now.

Unless we require a very specific feature available on a specific API level, we should use common sense and try to aim for as many devices as we can. Having said that, we should not waste time supporting very old devices (or very old versions of Android), as they might be, for example, only 5% of the active devices but may imply lots and lots of work to make your application support them. In addition to the minimum SDK version, there is also the target SDK version. The target SDK version should be, ideally, set to the latest stable version of Android available to allow your application to take advantage of all the new features, styles, and behaviors from newer versions.

As a rule of thumb, Google gives you the percentage of active devices on Google Play, not the percentage of devices out there in the wild. So, unless we need to build an enterprise application for a closed set of devices and installed ad hoc, we should not mind those people not even accessing Google Play, as they will not the users of our application because they do not usually download applications, unless we are targeting countries where Google Play is not available. In that case, we should analyze our requirements with real data from the available application stores in those countries.

To see the Android OS version distribution, always check the Android developer dashboard at http://developer.android.com/about/dashboards/index.html.

Alternatively, when creating a new project from Android Studio, there is a link to help you choose the version that you would like to target; this will open a new screen with the cumulative percentage of coverage.

If you click on each version, it will give you more details about that Android OS version and the features that were introduced, as shown in the following screenshot:

After this step, and to simplify our application creation process, Android Studio will allow us to add an Activity class to the project from some templates. In this case, we can add an empty Activity class for the time being. Let's not worry about the name of the Activity class and layout file at this moment; we can safely proceed with the prefilled values.

As defined by Android developer documentation an: Activity is a single, focused thing that the user can do. (Source: http://developer.android.com/reference/android/app/Activity.html)

To simplify further, we can consider an Activity class as every single screen of our application where the user can interact with it. If we take into consideration the MVC pattern, we can assume the Activity class to be the Controller, as it will receive all the user inputs and events from the views, and the layout XML and UI widgets to be the views.

Note

To know more about the MVC pattern, check out the following page: https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller.

So, we have just added one Activity class to our application; let's see what else the Android Studio wizard created for us.

Running your project

The Android Studio project wizard not only created an empty Activity class for us, but it also created an AndroidManifest, a layout file (activity_main.xml) defining the View controlled by the Activity class, an application icon placed carefully into different mipmaps (https://en.wikipedia.org/wiki/Mipmap) so that the most appropriate will be used depending on the screen resolution, some Gradle scripts, and and some other .xml files containing colors, dimensions, strings, and style definitions.

We can have multiple resources, and even repeated resources, depending on screen resolution, screen orientation, night mode, layout direction, or even the mobile country code of the SIM card. Take a look at the next topic to understand how to add qualifiers and filters to resources. For the time being, let's just try to run this example by pressing the Play button next to our build configuration named app at the top of the screen.

Android Studio will show us a small window where we can select the deployment target: a real device or emulator where our application will be installed and launched. If we have not connected any device or created any emulator, we can do it from the following screen. Let's press the Create New Emulator button.

From this new screen, we can easily select a device and create an emulator that looks like that device. A Nexus 5X will suit us. After choosing the device, we can choose which version of the Android OS and architecture the platform will run on. For instance, if we want to select Android Marshmallow (API level 23), we can choose from armeabi-v7a, x86 (Intel processors) and x86_64 (Intel 64bit processors). As we previously installed HAXM during our first run (https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager), we should install an Intel image, so the emulator will be a lot faster than having to emulate an ARM processor. If we do not have the Android OS image downloaded to our computer, we can do it from this screen as well. Note that you can have an image of the OS with Google APIs or without them. We will use one image or another depending on whether the application uses any Google-specific libraries (Google Play Services) or only the Android core libraries.

Once the image is selected (and downloaded and installed, if needed), we can proceed to finish the Android Virtual Device (AVD) configuration. On the last configuration screen, we can fine-tune some elements of our emulator, such as the default orientation (portrait or landscape), the screen scale, the SD card (if we enable the advanced settings), the amount of physical RAM, network latency, and we can use the webcam in our computer as the emulator's camera.

You are now ready to run your application on the Android emulator that you just created. Just select it as the deployment target and wait for it to load and install the app. If everything goes as it should, you should see this screen on the Android emulator:

If you want to use a real device instead of an emulator, make sure that your device has the developer options enabled and it is connected to your computer using a USB cable. To enable development mode on your device or get information on how to develop and debug applications over the network, instead of having the device connected through an USB, check out the following links:

If these steps are performed correctly, your device will appear as a connected device on the deployment target selection window.

Resource configuration qualifiers

As we introduced in the previous section, we can have multiple resources depending on the screen resolution or any other device configuration, and Android will choose the most appropriate resource at runtime. In order to do that, we have to use what is called configuration qualifiers. These qualifiers are only strings appended to the resource folder. Consider the following example:

drawable
drawable-hdpi
drawable-mdpi
drawable-en-rUS-land
layout
layout-en
layout-sw600dp
layout-v7

Qualifiers can be combined, but they must always follow the order specified by Google in the Providing Resource documentation, available at http://developer.android.com/guide/topics/resources/providing-resources.html.

This allows us, for instance, to target multiple resolutions and have the best experience for each of them. It can be also used to have different images based on the country in which the application is executed, or the language.

We have to be aware that putting in too many resources (basically, images or any other media) will make our application grow in size. It is always good to apply common sense. And, in the event of having too many different resources or configurations, do not bloat the application and produce different binaries that can be deployed selectively to different devices on Google Play. We will briefly explain in the Gradle build system topic in this chapter, how to produce different binaries from one single source code. It will add some complexity on our development but will make our application smaller and more convenient for end users. For more information on multiple APK support, visit http://developer.android.com/google/play/publishing/multiple-apks.html.

 

Additional elements


Now that we have already introduced some of the elements involved in the process of building mobile applications for Android devices, we will dive deep into some of them.

Resources

To build an application we do not only need source code, we also need some additional files such as images, text, layout description files, or others. Those additional files are what we call resources. Our project will contain a res directory together with our src directory. Inside this directory, we can find resources needed by our application.

To make our application as easy as possible to maintain and add new features to we should externalize resources such as application images and texts from the source code. It will keep our application code simple and we can easily add support for new countries or new languages for example. As explained earlier, we can have multiple resources and, thanks to the resource qualifiers, the Android device will pick the proper resource based on its properties in runtime.

For static files that need to be included without any kind of filter, you can use the assets folder. Everything there will be included into the final application. To access these assets, we will have to use the AssetManager class, but we will cover this later. Visit http://developer.android.com/reference/android/content/res/AssetManager.html for more information on the AssetManager class.

Modules

In order to keep the code of the application tidy and uncoupled, we can identify parts of the application, which might be even reused later in some other applications, that can be completely decoupled and exposed as a module. Gradle, the build system, allows us to have several modules and establish dependencies between the main application and those modules. To make it more interesting, these modules can be extracted as independent projects and have an independent release cycle as though we are using a third-party library. Modules can be considered as Android libraries or Android library projects. Instead of having third-party dependencies pulled from remote repositories, we have them inside our project. Visit https://developer.android.com/studio/projects/add-app-module.html for more information on modules.

Android Manifest

The Android Manifest file is our application descriptor. Here, we can find all the activities, services, content providers, and broadcast receivers defined in our application, the list of permissions required, which icon to use on the Application menu, and a lot of other configurations. For an exhaustive list of configurations, check the official documentation at http://developer.android.com/guide/topics/manifest/manifest-intro.html.

When the application is compiled, the manifest is transformed into a binary format. In order to see the manifest of a compiled APK, we can use the following tool, included with the Android SDK:

<Android SDK path>/build-tools/23.0.2/aapt dump badging <apk file>

On Mac OS, Android SDK will be installed inside your local Library directory, as ~/Library/Android/sdk/.

Gradle build system

Gradle (http://gradle.org) is the new build system recommended by Google. On previous versions, and before the introduction of Android Studio, Ant was the default build system used. Gradle is a DSL, or domain-specific language, that allows scripting for more complex build processes or configurations. You can do lots of things with it, but some of the most used parts of the Gradle build system are dependency management and the option to build different flavors (or configurations) of your application.

Dependency management is not only useful for managing internal modules, but also for managing external third-party libraries that we will use in our application.

If, for instance, we want to include Retrofit (HTTP client, http://square.github.io/retrofit/) and Picasso (the image downloading library, http://square.github.io/picasso/), we will have to add the two dependencies to our build.gradle file under the dependencies keyword:

dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  testCompile 'junit:junit:4.12'
  compile 'com.android.support:appcompat-v7:23.1.1'
  compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
  compile 'com.squareup.picasso:picasso:2.5.2'
}

We have just added the last two lines to the dependencies that Android Studio puts in by default.

Let's now discuss flavors, a very powerful way to build multiple configurations out of the same source code. If we take a look at Google Play, we will notice that there are many apps and games with a free version, usually limited or with ads, and a full or pro version.

Instead of duplicating all the code and having to build two different applications, adding two different flavors to your application allows you to have two or more different builds out of almost the same source code. Each flavor can have a specific source code and resources that will differentiate it from the other flavors, but at the same time each flavor will share the common source code and resources with all the others.

Let's modify our test application, the one created by the Android Studio Wizard, to add two flavors.

First, we need to add the two flavors to our build.gradle file. Here is the resulting file with the two flavors and the dependencies we introduced in the previous topic.

apply plugin: 'com.android.application'
android {
  compileSdkVersion 23
  buildToolsVersion "23.0.2"
  defaultConfig {
  applicationId "com.packt.rrafols.example"
  minSdkVersion 14
  targetSdkVersion 23
  versionCode 1
  versionName "1.0"
 }
 productFlavors {
   free {
     applicationId "com.packt.rrafols.example.free"
   }
   pro {
     applicationId "com.packt.rrafols.example.pro"
   }
 }
 buildTypes {
   release {
     minifyEnabled false
     proguardFiles getDefaultProguardFile('proguard-
     android.txt'),'proguard-rules.pro'
  }
 }
}
dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  testCompile 'junit:junit:4.12'
  compile 'com.android.support:appcompat-v7:23.1.1'
  compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
  compile 'com.squareup.picasso:picasso:2.5.2'
}

As you can see, there are two different flavors, free and pro, with different applicationId objects, so we can have both installed on any device at the same time.

Now, we go to Android Studio and create these directories:

  • app/src/free/java/com/packt/rrafols

  • app/src/pro/java/com/packt/rrafols

The shared part of the code will remain in app/src/java and the specific code for each flavor will go into its own directory. Let's create a dummy class named ApplicationName inside the directory we created for the free flavor with the following content:

package com.packt.rrafols;
public class ApplicationName {
  public static final String APPLICATION_FLAVOR = "free";
}

We will do the same for the pro flavor:

package com.packt.rrafols;
public class ApplicationName {
  public static final String APPLICATION_FLAVOR = "pro";
}

Now, we will have two classes with the same name but, no need to worry, only one of them will be included in our build, depending on which flavor we are building.

To show that this is working, let's modify the MainActivity class to change the title to the APPLICATION_FLAVOR value:

package com.packt.rrafols.example;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.packt.rrafols.ApplicationName;
public class MainActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getSupportActionBar()
    .setTitle(ApplicationName.APPLICATION_FLAVOR);
 }
}

We can choose which flavor to build from the Build Variants tab in Android Studio.

We can also achieve the same effect by having different resources in each flavor. Let's change our MainActivity layout, as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context="com.packt.rrafols.example.MainActivity">
 <TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/app_flavor" />
</RelativeLayout>

Next, let's create the property in the res/values/strings.xml directory:

<string name="app_flavor">No flavor specified</string>

To customize this message, we will have to create two resource folders, one for each flavor like we did before for the source code:

  • app/src/free/res/values

  • app/src/pro/res/values

In the free flavor resource folder, we will create a new strings.xml file with the following content:

<resources>
<string name="app_flavor">Application flavor: free</string>
</resources>

Also, we will do the same for the pro flavor:

<resources>
<string name="app_flavor">Application flavor: pro</string>
</resources>

Properties from our flavor will be merged with the default properties. Those that are equal will be overwritten by the flavor-specific value and the application will show the selected flavor message.

As an alternative to Gradle, if you have a very big application and the build time is one of your bottlenecks, you might even try Buck. Buck (https://buckbuild.com) is the build system developed by Facebook. It highly focused on build performance although the latest versions of Gradle are improving on performance, and Gradle is the tool selected by Google.

ProGuard

ProGuard is a code obfuscation tool. The Java compiler does not do a good job of optimizing the resulting class files when compiled from Java sources. By default, it preserves all the variable names, method names and code is quite easy, not to say straightforward, to decompile to high-level code once again. There are many tools out there that allow us to do that, for example, smali (https://github.com/JesusFreke/smali) or dedexer (http://dedexer.sourceforge.net/). To make it difficult for anyone else to peek into our code, it is always recommended that we run ProGuard to obfuscate (or minify) the compiled version of our application. Not only will it replace all our class names, methods, and variables with single-letter strings (a, b, ..), but it will also slightly optimize the compiled bytecode and make it more complex (although not impossible) for hackers to hack our application. We should not rely only on ProGuard for the security of our application, but we can say that ProGuard is an additional barrier that we add to our application.

To enable ProGuard, we have to make a small change to our build.gradle file in our app folder:

release { 
  minifyEnabled false
  proguardFiles getDefaultProGuardFile('proguard-android.txt'),
  'proGuard-rules.pro'}

By just changing minifyEnabled to true, we are telling Gradle that it has to run ProGuard on the release build.

ProGuard needs to be configured properly to do a good job; we cannot just obfuscate the whole enchilada. The ProGuard configuration file tells ProGuard, among other things, which classes or methods need to be preserved. There are some methods that need to be retained as Android expects them to be there and, when using third-party libraries, always double-check the ProGuard requirements of those libraries, as they might come with their own set of rules. As an example, if we use retrofit, which will be introduced in Chapter 5, Remote Data, we will have to add the following set of rules:

-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions

Note

For more information about rules and how to configure ProGuard properly, check out its official website and documentation at http://proguard.sourceforge.net/manual/introduction.html.

We can add these rules to the proguard-rules.pro file, as it is specified in the build.gradle section that we modified before enabling ProGuard.

Even though Android does not use the bytecode produced by the Java compiler directly, prior to Android 5.0, we had the DALVIK VM, which converted the java bytecode to DALVIK (DEX) bytecode, and now, with the introduction of ART, bytecode is compiled into native code for the sake of performance. So, to sum this up, all the resulting code, either DEX or native, is produced from the original Java bytecode, so optimizing it will definitely make a small improvement to the final code that will be run by the Android device. For more information, check out what I discussed at the talk in Droidcon, Amsterdam in late 2014 (http://blog.rafols.org/wp-content/uploads/droidcon_nl_android.pdf).

Another issue where ProGuard might help is with the 64k method limit. There is a design flaw on the DEX file specification that only allows 65536 methods to be referenced on each DEX file (http://developer.android.com/tools/building/multidex.html).

This is much of a problem for a simple application, but if we start adding lots of third-party libraries or our application is relatively complex, it can be a problem. For example, if we have to include the whole Google Play Services, it will already add 38k methods to our application. Now, Google Play Services is split into several smaller packages, and we can include only the parts that we require. Nevertheless, if we enable minification or, basically, ProGuard, it will remove all unused methods from both our application and the libraries we include, drastically reducing the total number of methods we will end up having in our application.

If you are concerned about security and would like to go the extra mile, I suggest that you go for DexGuard (https://www.guardsquare.com/dexguard); it is not free, but has more features than ProGuard and it is developed and maintained by the same company as ProGuard.

 

Summary


In this chapter, we covered how to install Android Studio and get started with it. We also briefly covered some of the additional parts or components that we will use in addition to the source code to build our application resources, Gradle build system, obfuscation, and Android Manifest.

About the Authors
  • Raimon Ràfols Montane

    Raimon Ràfols is a Software Engineer currently living in the Barcelona area. He has been working on mobile devices since the early ages: from monochrome devices to the current smartphones. In all these years he worked in several areas: B2C/B2E/B2B apps, portals and mobile gaming. Due to this broad experience, he has expertise in many technologies and, especially in UI, build systems and client-server communications. He is currently working as Engineering Manager at AXA Group Solutions in Barcelona, taking care of all the engineering and development processes, mobile application quality and leading a small R&D team. In the past, he has been working abroad for Imagination Technologies near London and for Service2Media in the Netherlands. In his spare time he enjoys taking part in hackathons, photography and giving talks in conferences. Raimon has won more than 40 international awards including AngelHack Barcelona 2015, Facebook World Hack Barcelona and 2nd place at js1k 2016. He has been speaking about Java/Android performance and bytecode, Android custom views and about entrepreneurship in several conferences around the world. I would like to thank my girlfriend for her support and understanding during the late night and lengthy writing weekends. Also, I would like to thank my parents and cousin, as without their support and encouragement, I would not be doing what I do today. Last, but not least, I would like to thank everyone that challenged me and help me grow up during my professional career. People like Carlos Carrasco, Alfred Ferrer, Pau Vivancos, Miquel Barceló, David Domingo, Marcel Roorda, Diego Morales, Alberto Chamorro, Teun van Run, Tom van Wietmarschen, Josep Cedó, Joanne Pupo, Jordi Valldaura, Mathieu Sivade, Chris Jakob, Tomas Kustrzynski, Bartłomiej Żarnowski, Radosław Holewa and those I have forgotten to mention here.

    Browse publications by this author
  • Laurence Dawson

    Laurence Dawson is a software developer and an academic focused on mobile development. He received a PhD in 2015 from Durham University, developing efficient parallel implementations of algorithms for GPUs using NVIDIA CUDA with an emphasis on metaheuristics and image processing. Laurence currently runs his own mobile software development company and is also a guest lecturer at King's College London, teach software engineering modules. You can follow his projects on his GitHub page at https://github.com/laurencedawson.

    Browse publications by this author
Latest Reviews (2 reviews total)
The Packt website is well set up and easy to navigate.
Good book but watch out, it doesn't match the 3.0 ANDROID development software.
Learning Android Application Development
Unlock this book and the full library FREE for 7 days
Start now