Introduction

Android OS has several releases over the past 2 years. These updates have introduced astonishing features thus causing several significant functionalities to become deprecated. This technological evolution has led to Android development challenge of keeping an app compatible with the different levels of Android OS, while keeping UI and UX elegant.

Throughout this tutorial, You will learn about how you can implement UI, UX, code quality, security, and third party libraries, along with tips and tricks to boost the quality of application with minimal efforts.

Quick Start Guide

The following guide will give you an instant notion about the basic android development terminologies in simplest terms, that is being used throughout this tutorial.

View: A View represents a graphical rectangular on the screen. Every GUI component like Button, TextView, EditText are inherited from View class.

ViewGroup: A ViewGroup is a layout container, which is responsible for positioning multiple views on the screen. There are various decedents of ViewGroup like LinearLayout, RelativeLayout, ConstraintLayout etc, to position child views in linear or relative fashion.

Activity: An Activity is a single screen view that is visible to user. An application can consist multiple Activities for separate functionalities, for e.g splash, Login , signUp etc.

1
2
3
4
5
6
7
8
9
10
11
// To create activity, a class must extend Activity or AppCompatActivity class// AppCompatActivity is used to support ActionBar and design features for older versionpublicclassMainActivityextendsAppCompatActivity{@OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);// static view for MainActivitysetContentView(R.layout.activity_main);}}

java

Using a backward compatibility component from a support package requires additional dependencies, which will result in increasing the APK size.

Layout XML file: XML is a tag based file which represents a static layout design view, which can be embedded into activities. A layout file can be attached to an Activity by calling setContentView(int) method.

A single XML file can be attached with multiple activities and there are many types of XML files, to design menu, shapes, selectors or to store global constant values.**

The design can also be created at run time (while the app is running) using Java or Kotlin code. This is helpful when you have no idea about the number of views to be drawn on the screen in dynamic environment.

Application: An application is a single entity which represents the whole app. It is the first instance to be initialized by Android OS, so often being used to declare global constants or configure services like crash-reposting, analysis, dependency injections which are required to run the app.

You can provide your own implementation by creating a subclass and specifying the fully-qualified name of this subclass as the "android:name" attribute in your AndroidManifest.xml's tag.

LifeCycle: LifeCycle corresponds to a series of methods which will be invoked by the Android OS according to the current state of the process. LifeCycle methods are described below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
publicclassMainActivityextendsAppCompatActivity{// called only once when activity is created// so optimal place to initialize GUI component and services@OverrideprotectedvoidonCreate(Bundle savedInstanceState){...};// called everytime when user comes to this activity@OverrideprotectedvoidonStart(){...};// called when activity is completely visible@OverrideprotectedvoidonResume(){...};// called when activity is partially visible// covered by some dialog@OverrideprotectedvoidonPause(){...};// called when current activity is covered by another activity// when user go to next activityprotectedvoidonStop(){...};// called when activity's object is destroyed and no longer accessible// when user press back-press button@OverrideprotectedvoidonDestroy(){...};}

java

These methods are invoked in a serial order in normal scenarios. There are many other methods, which can be overridden when required, as shown in below image.

Context : A context is a special object which is used to access the resources and files (assets, XML constants) contained in application. Activities has their own context and can be used as YourActivityName.this which is internally initialized by Application object.

getContext() will give current host activity's context and getApplicationContext() will give the context of the application. These methods are not accessible in normal classes but they can be passed as values.

Manifest : manifest.xml contains information about app which is required by android OS to grant permission to access resources like storage, Internet, SMS and registered activities etc. Every activity or customize application class (if there is any) should be registered in manifest.xml.

Gradle: The build system used to download dependencies, tools and to manage application configuration settings to build project.

There are two gradle files:

Project : which is used to configure project and sub-projects

Module : which is used to configure app, dependencies,SDK versions etc.

R.java: A final Java class file that consists of static final int constants and array constants. Every file or unique id ([email protected]/name attribute of views), is given an int value by the gradle and these constants are used to access those components and files in project.

This file is created under app\generated\source\r\debug\your_package_name\R.java directory and should never be modified by hand.

The R file is especially useful when trying to get access views in code. For example, the View method findViewById() takes in an R.id value based on the component to be selected, such as R.id.my_button.

Design

An Android application should provide a simplified, engaging interface with meaningful motion like elevation, ripple, and material design.

Android 5.0 Lollipop introduced the concept of Material design, which can also be implemented on older versions by using the Android Design library which provides material design components to make an elegant app.

Steps to include design library as dependency

Open build.gradle (module)

Add the following dependency inside the dependencies block

1
compile 'com.android.support:design:27.0.2'

or use implementation for Android studio 3.0. Note that the version number 27.0.2 may differ in to future releases:

1
implementation 'com.android.support:design:27.0.2'

FloatingActionButton (fab)

A FloatingActionButton (fab) is a round button with an icon, which denotes a quick primary action on the interface such as:

Adding a Note or alarm

Sending an email or text

Snackbar

Snackbar appears from the bottom for a short time then disappears. It shows a brief message along with an action button to perform corresponding task. Using the SnackBar is best when trying to:

Undo the item deletion

Display an exit action when back button pressed

Move up the Fab when SnackBar appears

If fab button is at the bottom of the screen, you can coordinate with the SnackBar to move the fab up when the SnackBar appears. This is done by using coordinator layout as the root ViewGroup.

Code Optimization

Serializable and Parcelable

Serialization is the process of converting your object into bytes to persist them. This can be achieved by implementing both the Serializable and Parcelable interfaces.

The important difference is that Parcelable is implemented via the Android native (C++) framework which requires less resources per single instruction resulting in overall better performance. Serializable is best when sending singular objects from one activity to another. Parcelable is far better for larger transfers, however, such as sending lists of customized objects to the next Activity. Learn more about the difference here.

OutOfMemoryError

Like every system, the Android OS has limited resources, so it's always better to avoid using large size bitmaps or images. There are other options that be applied, such as

LinearLayout

To achieve better performance for simple layout(without multiple nested ViewGroups), it is preferred to use LinearLayout due to support of linear flow-based UI drawing whereas the Relative layout always use two measure passes.

LinearLayout is also quite handy for allocating the available width or height as per the weight property.

Set the attribute value as 0dp of either height or width

As per the weight property, 0dp of space (either height or width) will be allocated.

To Record a test:
Click "run" in menu
Select "Record Esprsso Test"
This will open the app on a device and record user actions, generating a UI test.

Best Practices

Security

An APK is like an archive. It contains a classes.dex archive which is a collection of .class files.

Anyone having access to dex2-jar tool can obtain the original source code (java files) and can build a personal version of your market app to harm your product value by uploading a free version of your app.

Proguard-rules.pro

This file contains the instructions to obfuscate source code for release apk. ProGuard is a command line tool that shrinks the size of apk by optimizing, obfuscating and eliminating the files (java/bytecode/resources) which results in smaller size apk.

The above configuration is for testing purposes. It will obfuscate the APK for every build. Please do not use the minifyEnabled true for debug because it will result in longer project buld duration.

Often you might be required to disable obfuscation for POJO classes and libraries to meet proper naming convention during JSON parsing or placing network calls. To accommodate for this, you can define customize rules for which code to keep.

Resources

Hide Sensitive Information

There is basically no way that you can protect your API key from a hacker but the safest way is to use an NDK, or a Native Developers Toolkit. Through the NDK, corresponding C and C++ functions can be implemented in Android project.

The NDK ports C and C++ code into separate libraries that are hard to decompile — although the NDK compiled code can still be opened with hexadecimal code, it is still hard to detect an API key out of hex code.

API Levels

Every Android release introduces new features that might not be backward compatible with older versions, making it important to make your app compatible with older versions. You can put a check to verify the current android OS version and process according as

Common Issues:

Do not reinvent the wheel

Android has a huge open source development community and there are thousands of developers who has published their great work in open source community which saves lot of time and efforts while offering tons of features.

For example, do not use background threads to download and display images just because you can write lengthy code — use Picasso, an image downloading library which offers lot other functionalities like cache, resizing, error handling and easily customizable.