如何使用Proguard混淆android库(.aar)?

如何使用Proguard混淆android库(.aar)?

问题描述:

我想使用proguard混淆 .aar 库以进行分发,我尝试了Internet上的许多解决方案,但到目前为止没有任何效果,仅混淆了一些代码.有人可以帮助我解决问题吗?

I want to obfuscate the .aar library using proguard for distribution purpose, I tried many solution over internet but nothing has worked till now, only some code are obfuscated. Can anybody help me to solve the issue?

在build.gradle中,在defaultConfig下添加consumerProguardFiles:

In your build.gradle, add consumerProguardFiles under defaultConfig :

 android {
        compileSdkVersion Integer.parseInt("${COMPILE_SDK}")
        buildToolsVersion "${BUILD_TOOLS_VERSION}"

        defaultConfig {
            targetSdkVersion Integer.parseInt("${TARGET_SDK}")
            minSdkVersion Integer.parseInt("${MIN_SDK}")
            consumerProguardFiles 'consumer-proguard-rules.pro'
        }
    }

您在库项目的根文件夹下添加了一个名为Consumer-proguard-rules.pro的文件.该文件应包含您的库项目的build.gradle中提到的所有依赖关系的proguard规则.您应该为POJO类,带有注释的接口以及需要保护其免受Proguard清洗或混淆的任何其他类添加一个keep规则. 如果收缩资源,则应在资源下的res(例如res/raw)下添加一个keep.xml文件.在此文件中,指定要保留的图形或布局.您可以检入代码,并使用反射通过getResources().getIdentifier(..)调用资源,如果这样的话,您可以添加这样的可绘制对象.

You add a file named consumer-proguard-rules.pro under the root folder of your library project. This file should contain all the proguard rules of the dependencies mentioned in the build.gradle of your library project. You should add a keep rule for your POJO classes, interfaces with annotations and whatever other class that you need to be kept safe from proguard cleaning or obfuscation. If you shrink resources, you should add a keep.xml file in your resources under res (res/raw for example). In this file you specify the drawables or layouts to keep. You check in your code in you use reflexion to call a resource with getResources().getIdentifier(..), if so you add your drawables like this.

<?xml version="1.0" encoding="utf-8"?>
<resources
    xmlns:tools="http://schemas.android.com/tools"
    tools:shrinkMode="safe"
    tools:keep="@layout/layout1, @drawable/icon1,@drawable/icon2,@drawable/img_*"/>

您可以使用*告诉Proguard将所有以img_开头的可绘制对象保留在可绘制文件夹中.

You can use * to tell proguard to keep all the drawables that start with img_ under the drawable folder.