Gradle插件開發 APK瘦身資源自定義7z壓縮

APK瘦身實戰 資源自定義7z壓縮

項目開發中,隨着業務的增長,常常需要在apk編譯階段對包代碼或是資源做一定的自定義修改,比如熱修復,插件生成,無埋點統計,渠道包生成等等。

但是公司項目業務開發人員基本上都很少接觸到相關技術,這裏以學習的態度,實現一套用7zip壓縮apk資源文件的gradle插件。

APK瘦身在行業內已經有很多成熟的開源技術體現方案,如美團Android App包瘦身優化實踐這篇博客中詳細的說明。
這裏我們從資源壓縮入手,用7z工具,實現一套自己的資源壓縮gradle插件。

Gradle 插件簡單介紹

一般簡單的邏輯可以寫在build.gradle文件中,但是本着便於管理及重用,可以把插件獨立爲項目。
獨立的gradle插件編譯後,我們可以發佈到本地maven庫,或是jcenter中心,供其他項目引用。

項目結構介紹

Gradle插件開發可以用android studio,也可以用IntelliJ。AS開發需要自己創建插件項目結構,而IntelliJ可以自動生成項目結構,但是用起來一些操作不是很順手。

如下圖,用IntelliJ New出來一個項目,按照引導,即可生成我們的初始項目結構及gradle-wrapper。

IntelliJ
這裏填寫插件 GroupId,ArtifactId,已經插件版本Version。如果不確定,可以先隨意寫個,隨後可以在項目中更改。

IntelliJ

標準的項目結構如下:

項目結構

如果用as開發,需要手動創建如上結構。從項目中可以看出支持groovy,和java的混合開發,當然從IntelliJ創建項目引導可以看出同時也是支持kotlin的。
每種語言都有各自的語言特點,比如我們開發gradle插件,在與項目build編譯交互的地方用groovy開發,業務的核心代碼用我們擅長的語言(java)開發,這裏使用7zip的地方就是用java封裝實現的。

項目結構

resources文件夾比較重要,這裏的文件標明瞭插件的入口,及插件的引用名字。如果導出maven庫找不到自己插件引用,可以先檢查下這個文件結構是否正確。

apk-shrink.properties

implementation-class=win.canking.gradle.ShrinkPlugin
apply plugin ‘apk-shrink

當build.gradle 解析 apply plugin 時,就會找到 win.canking.gradle.ShrinkPlugin, 開始執行apply()方法

項目可能遇到的問題

1,發佈本地maven,build.gradle配置如下

apply plugin: 'groovy'
apply plugin: 'java'
apply plugin: 'maven'

group 'win.canking.gradle'
version '1.0.1'
archivesBaseName = 'apk-shrink'//ArtifactId默認是項目module name

compileGroovy {
    sourceCompatibility = 1.7
    targetCompatibility = 1.7
    options.encoding = "UTF-8"
}

dependencies {
    compile gradleApi()
    compile localGroovy()
    compile 'com.android.tools.build:gradle:2.1.0'
}

uploadArchives {
    repositories.mavenDeployer {
        //文件發佈到下面目錄
        repository(url: uri('../../xxx/gradleplugin/'))
    }
}

執行如下代碼,可以生成本地的maven庫

gradlew -p {module name} clean build uploadArchives --info

2,不同JDK編譯問題,特別注意,需要配置sourceCompatibility

3, 引用找不到問題
先檢查導出目錄,是否生成了maven。目錄結構如下:

maven

反編譯生成的jar包,查看打包是否正確。

JD-gui

APK資源自定義壓縮

APK包結構

一個apk文件本質上就是一個zip壓縮文件,我們可以用解壓縮工具解壓查看內部結構。

name desp
res 資源文件,該文件下資源都會映射到項目R文件中,生成引用ID
assets 靜態資源文件,訪問是需要用到 AssetManager
lib 第三包jar或者native so庫
META-INF 簽名信息,CERT.RSA CERT.SF MANIFRST.MF
AndroidManifest 項目清單文件,包含四大組件,包信息,權限等
classes.dex java的class文件通過dx工具生成的安卓執行文件
resources.arsc 編譯後的二進制資源文件,包含代碼對資源的引用關係

資源文件壓縮

aapt l -v xxx.apk

stored

從圖中看出apk中有些資源文件存儲方式爲stored,是未經壓縮狀態,我們可以對apk再處理,通過高壓縮率的工具(7zip)壓縮文件,達到瘦身目的。

獲取7zip工具路徑

通過“which 7za“獲取PC上7zip工具目錄

        ProcessBuilder pb = new ProcessBuilder(new String[]{"which", "7za"});
        String sevenZipPath = "";
    try {
            Process process = pb.start();
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String tmp;
            while ((tmp = input.readLine()) != null) {
                if (tmp.endsWith(File.separator + "7za")) {
                    sevenZipPath = tmp;
                    Log.a("Shrink", "7zip path:" + sevenZipPath);
                }
            }
            process.waitFor();
            process.destroy();
        } catch (Exception e) {
            Log.e("Error", "no shrink" + e.getMessage());
            return;
        }

定義要壓縮的文件類型:

 public class CompressInfo {
    public Set<String> compressFilesPattern;

    private CompressInfo() {
        this.compressFilesPattern = new HashSet<>();
    }

    public static CompressInfo init() {
        CompressInfo info = new CompressInfo();
        info.compressFilesPattern.add(".png");
        info.compressFilesPattern.add(".jpg");
        info.compressFilesPattern.add(".JPG");
        info.compressFilesPattern.add(".jpeg");
        info.compressFilesPattern.add(".gif");
        info.compressFilesPattern.add(".arsc");
        return info;
    }
  }

調用7za進行壓縮目標文件

    private static void do7zip(String srcDirPath, String outZipPath, String sevenZipPath)
            throws IOException, InterruptedException {
        String srcFilesPath = new File(srcDirPath).getAbsolutePath() + File.separator + "*";
        outZipPath = new File(outZipPath).getAbsolutePath();

        ProcessBuilder pb = new ProcessBuilder(new String[]{sevenZipPath, "a", "-tzip", outZipPath, srcFilesPath, "-mx9"});
        Process process = pb.start();

        InputStreamReader ir = new InputStreamReader(process.getInputStream());
        LineNumberReader input = new LineNumberReader(ir);
        String line;
        while ((line = input.readLine()) != null) {
            Log.d(input.getLineNumber() + ":" + line);
        }
        process.waitFor();
        process.destroy();
    }

指定task來執行壓縮任務

    @Override
    void apply(Project project) {
        Log.d("shrink apply")
        if (project.getPlugins().hasPlugin(AppPlugin)) {

            def config = project.extensions.create(SHRINK_CONFIG, ShrinkExtension)
            project.afterEvaluate {
                project.tasks.matching {
                    println it.name
                    it.name.startsWith('packageRelease')
                } each {
                    t ->
                        t.doLast {
                            if (config.enable) {
                                Log.d("shrink start...")
                                GradleMrg.do7zipCompressApk(config.apkPath)
                                Log.d("shrink EDN")
                            }
                        }
                }
            }
        }
    }

項目也可以自定義一個單獨的task,不依賴編譯流程。

壓縮效果對比:

shrink after
shrink before

本案例源碼已提交到GitHub,歡迎交流學習。


歡迎轉載,請標明出處:常興E站 canking.win

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章