Android

4 Ways To Reduce APK Size

APK, Android Application Package, is in a zip file format. The Java/Kotlin/C++ code, and resources we are using in our android application are compiled and compressed into APK file.

When a user installs an application from the Google Play store, it downloads its APK file and stores it in the data folder which is created by the APK manager for the application. The storage area is taken from the internal space of the device.

Since each application is occupying internal storage space of the device, the user is concerned about the APK size. And it is quite natural to ignore the application with large size even if they are interested in it.

So APK file size plays a crucial role in increasing the install of an application in Google Play store. Application with lesser APK size gets more installs than its competitors with larger APK size.

Here in this article, I will talk about some tips to reduce the APK size.

The modern concept of APK size optimisation is based on 2 principles. They are as follows,

  1. Avoid bundling contents in APK file.
  2. Compress the contents in APK file.

The modern evolving concepts of dynamic content delivery and high quality compression methods are getting serious attentions from Android development world.

Based on the above two core principles of size optimisation, I further subdivide them into 4 points for your easier understanding.

Following are the major 4 solutions

  1. Use Android App Bundles
  2. Use Multiple APKs
  3. Use ABI filters
  4. Code level and resource level optimizations

Before getting into these 4 solutions, I highly recommend you to use APK Analyzer tool of Android Studio. With this tool, you can very easily understand which part of your APK is taking more space.

Based on the insight you got through Analyzer, you have to pick the right solution.

1. Android App Bundle

This is a service offering from Google Play store. If you are distributing your Android application through Google play store then this is one of the best options to distribute your application to users.

Android App Bundle is a new upload format to Google Play store. This is based on Google’s new APK serving mode called “Dynamic Delivery”.

If you are using Android Studio 3.2 >= then, you will get an additional option in “Generate Signed Signed APK” menu. Where you can create App bundles instead of generating APK file.

Google Play will use your app bundle to generate and serve optimized APKs for each user’s device configuration, so they download only the code and resources they need to run your app.

You no longer have to build, sign, and manage multiple APKs to support different devices, and users get smaller, more optimized downloads.

2. Multiple APK files

This is gradle based option to create separate APK files based on the device configurations. Users with different configuration will get different APKs.

In this case, we upload APK itself, but instead of a single APK file, we will upload multiple APK files based on different configurations that are defined in our code.

We can mainly configure APK based on,

  1. Density (mdpi, xhdpi, xxhdpi, xxxhdpi etc)
  2. ABI filters (If you use Native Libraries)

The above two items mainly act as filters when an Application runs. If a user is running our app on an xxhdpi device then, the rest of the resources provided are useless for his device.

3. ABI Filters

Use ABI filters of gradle to exclude unwanted Native libraries are being bundled to APK. Native libraries takes higher storage space. You can see that through APK Analyzer tool.

If you are using Native libraries in your app then the system will generate native libraries for each CPU architectures like ARM, x86, MIPS. Each architecture, in turn, supports multiple instruction sets.

You know that most of the device in the market is using ARM architecture, so you want to exclude the libraries of x86 and MIPS. For that, you can use ABI filters in gradle to remove the support for them like following,

buildTypes {
release {
ndk {
abiFilters "arm64-v8a", "armeabi-v7a"
}
}

4. Code/Resource Level Optimizations

These are mainly some guidelines that should be followed during the time of development.

Always Use Recommended Media Types

Image, Video and Audio Files are the biggest file types used in an app. Avoiding these media types are inevitable for applications nowadays as applications have come with high-quality graphics. So we identified usage of the media types is the first most key area to be optimized.

As per Android Official Team about Mediatype to be used they recommend us to choose some specific media type. Which are categorized by image, video and  sound,

For Icons : SVG is the best. Android Studio has built-in Vector Asset Studio. Not only it has a collection of frequently used icon sets but also you can import external SVG files created by other software.

If you want to use a simple shape like a rectangle, circle or triangle then isshape drawable recommended.
Reference : https://devdeeds.com/create-triangle-shape-using-xml-android/

For Images: Recommended to use WebP modern image format. Android Studio gives support to convert existing PNG, JPEG etc image resources to convert to corresponding WebP format with a single click.

WebP lossless images are 26% smaller in size compared to PNGs. WebP lossy images are 25-34% smaller than comparable JPEG images at equivalent SSIM quality index.

For Fonts: Use Downloadable fonts which is introduced in Android 8.0 (API Level 26). It gives Google Font Provider API to avoid bundling of TTF files.

For VideosH264 AVC. Encode the video to a resolution no larger than the screen resolution of the target device (if known).

For AudiosAAC (Advanced Audio Coding) format is recommended officially. AAC generally achieves better sound quality than MP3 at similar bit rates. AAC is the standard audio format for YouTube, iPhone, iPod, iPad etc

Optimize/Compress Media Types Using Tools

You can compress PNG and JPEG files without losing image quality. There are several online tools available. Optimizing resolutions of both images and videos can reduce the file size.

PNGCrush
OptiPNG
GetPaint

are some examples. There are many online image compressing services are available.

Use Individual APIs And Avoid Unused Codes

When setting up Google Play Services there are two options for you. First one is to use add dependency of complete API as single line of code and other option is to add individual API. If you want the functionalities of Google fitness and wearable then using complete set of API will make large amount of unused code. Individual APIs can save significant amount of size

build.gradle

Complete API dependency

compile 'com.google.android.gms:play-services:9.0.2'

Replace them it with,

compile 'com.google.android.gms:play-services-fitness:9.0.2'
compile 'com.google.android.gms:play-services-wearable:9.0.2'

reference:
https://developers.google.com/android/guides/setup
Logging is useless when apk is in release mode. It wastes spaces of the apk and degrade performance of the app. In our development time we log information for many purpose. In such case wrap it in universal constant variable so based on the value of this variable logging will perform.

if (ALLOW_LOGGIN) {
Log.d("MainActivity error", e.getMessage());
}

Use Proguard And Lint

This is the final step. Progaurd is a multi-purpose tool. It minify the java source code and obfuscate the source code. It will go through each line of code and detect unused codes. Detected unused code will be later removed and rename the length names to shorter form.

In build.gradle file

release {          
            minifyEnabled true
            proguardFile getDefaultProguardFile('proguard-android.txt')
        }

When you use Proguard the source code will be like this,

obfuscated_code

Always update Gradle Plugin Version of your project to get new features and performance improvements to the build system.

From Android Gradle Plugin Version 3.4.0, Plugin uses R8 compiler to perform tasks like, shrink, obfuscate and optimize the app in one step.

Lint : The Lint tool checks your Android project source files for unused resources such as layout files, drawables and assets. It can list the resources which are no longer in use in the application as warnings.

Command-Line:

lint [flags]

in build.gradle

android {
    lintOptions {
       // set to true to turn off analysis progress reporting by lint
       quiet true
       // if true, stop the gradle build if errors are found
       abortOnError false
       // if true, only report errors
       ignoreWarnings true
       }
       ...
    }

Note: Apart from the above solutions the way you develop is the most important thing. If you code intelligently i.e, replacing graphical images with proper XML based shapes and gradients , re-usage of graphics and layouts, downloading of assets from server. Replaying on Google play services is good choice because it does not require you to provide the source code of the functionality instead it will call the built-in service of the Android device.

About author

Rojer is a programmer by profession, but he likes to research new things and is also interested in writing. Devdeeds is his blog, where he writes all the blog posts related to technology, gadgets, mobile apps, games, and related content.

Leave a Reply

Your email address will not be published. Required fields are marked *