zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

【Android 安装包优化】资源打包配置 ( resources.arsc 资源映射表 | 配置国际化资源 )

2023-06-13 09:17:50 时间

文章目录

一、resources.arsc 资源映射表


分析 Android 应用打包后的 APK 文件 , 打开 resources.arsc 文件 , 该文件是 Android 应用的资源映射表 ,

点击 string , 查看字符串资源 , 在 strings.xml 中定义的字符串 , 都在打包在了该位置 ;

在该资源映射表中的 string 字符串 , 包含了所有语言类型 , 浪费了很多不必要的空间 ;

这些字符串很多都是国际化时用的 , 查看项目源码 , 发现 res 资源目录中 , 并没有进行国际化 , 这些国际化资源都是随着依赖库引入而进入到应用中的 , 国际化资源最多的就是 androidx.appcompat:appcompat 依赖库 , 配置了所有国家语言的国际化资源 ;

二、配置国际化资源


在 build.gradle 构建脚本中的 " android / defaultConfig " 层级配置 resConfigs ‘en’ , 配置后只打包默认资源与英文资源 , 不会打包其它语言的国际化资源 , 最大限度节省空间 ;

android {
    defaultConfig {
        // 国际化资源配置, 只打包默认资源与英文资源
        resConfigs 'en'
    }
}

配置完毕后 , 选择 " 菜单栏 / Build / Build Bundle(s)/APK(s) / Build APK(s) " , 再次编译生成 APK 安装包 ;

此时就可以看到 APK 减小了

\rm 1 MB

, 由

\rm 3.9 MB

, 减小为

\rm 3.8 MB

;

原来的 resources.arsc 资源映射表文件 , 由

\rm 704.6 KB

减小为

\rm 366.9 KB

;

文件中几十种语言的国际化资源只剩下一个默认资源 ;

资源越多 , 该配置减小的体积就越多 ;

三、完整 build.gradle 构建脚本示例


plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "kim.hsl.svg"
        minSdkVersion 18
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

        // 生成 PNG 图片配置
        //generatedDensities = ['hdpi', 'mdpi', 'xhdpi',  'xxhdpi', 'xxxhdpi']

        // 使用 com.android.support:appcompat 支持库配置
        vectorDrawables.useSupportLibrary = true

        // 国际化资源配置, 只打包默认资源与英文资源
        resConfigs 'en'
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'

    // 矢量图支持库 , 支持 5.0 以下版本手机使用矢量图 , 这个是创建应用时自带的配置
    implementation 'androidx.appcompat:appcompat:1.2.0'

    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

四、参考资料


博客资源 :