App size optimization helps make your app smaller. Smaller apps download faster and use less space on phones.
0
0
App size optimization in Android Kotlin
Introduction
When your app is too large and users complain about download time.
When you want to reduce data usage for users with limited internet.
When you want to improve app install rates on devices with low storage.
When you add many images or libraries and want to keep app size small.
Syntax
Android Kotlin
android {
defaultConfig {
}
buildTypes {
release {
// Enable shrinking and obfuscation
minifyEnabled true
// Remove unused resources
shrinkResources true
// Use ProGuard or R8 rules
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}minifyEnabled removes unused code and obfuscates names.
shrinkResources removes unused resources like images and strings.
Examples
Disables code shrinking and resource shrinking. App size will be larger.
Android Kotlin
minifyEnabled false shrinkResources false
Only code shrinking is enabled. Resources are not removed.
Android Kotlin
minifyEnabled true shrinkResources false
Both code and resource shrinking are enabled. Best for smaller app size.
Android Kotlin
minifyEnabled true shrinkResources true
Sample App
This is a minimal Android app setup with code and resource shrinking enabled for release builds. It uses a simple built-in layout to keep size small.
Android Kotlin
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdk 33
defaultConfig {
applicationId "com.example.appsize"
minSdk 21
targetSdk 33
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
// Simple MainActivity.kt
package com.example.appsize
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(android.R.layout.simple_list_item_1)
}
}OutputSuccess
Important Notes
Always test your app after enabling shrinking to avoid removing needed code or resources.
Use ProGuard or R8 rules to keep important code from being removed.
Large images can be compressed or replaced with vector graphics to save space.
Summary
Enable minifyEnabled and shrinkResources in your build config to reduce app size.
Use ProGuard or R8 to remove unused code and rename classes.
Test your app carefully after optimization to ensure it still works well.