在Android中使用新版proguard混淆器的方式

文章目录

一、Proguard混淆器

Proguard是Android开发时经常会用到的一个混淆工具,在Android SDK中已经集成了一个免费的Proguard版本,位于/tools/proguard目录中。对于Android中如何使用这里不在记录,新版的用法与Android自带的Proguard引入方式不同,语法一样。本文记录如何使用新版的混淆器。

为什么要使用新版的混淆器,这是因为Android自带的版本较旧,有些特性不支持。假如我想将androidx.core.**混淆,其余的包保持不变。那么使用Android自带的方式是无法做到的(当然将每一个包的文件写出来也是可以的,但是及其繁琐),所以需要使用新版的混淆器。

使用方式有两种,一种直接在项目中引入插件,但是该方式会导致与R8编译器冲突。另外一种是下载安装包替换/tools/proguard目录中的文件,不过在协作开发时候该方式会很麻烦。

二、新版混淆器使用方式(插件版)

这里根据gradle的依赖版本有两种写法,这里记录高版本的写法,使用范围
ProGuard Gradle 插件(AGP 版本 4.x - AGP 7.x)

根目录下面
<project>/build.gradle

groovy 复制代码
buildscript {
    repositories {
        google()       // For the Android Gradle plugin.
        mavenCentral() // For the ProGuard Gradle Plugin and anything else.
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:x.y.z'    // The Android Gradle plugin.
        classpath 'com.guardsquare:proguard-gradle:7.1.0'  // The ProGuard Gradle plugin.
    }
}

app/build.gradle

groovy 复制代码
 apply plugin: 'com.android.application'
 apply plugin: 'com.guardsquare.proguard'

由于ProGuard 期望未混淆的类文件作为输入。因此,必须禁用其他混淆器(例如 R8)。

groovy 复制代码
android {
    ...
    buildTypes {
       release {
          // Deactivate R8.
          minifyEnabled false
       }
    }
}

所以apk不能进行压缩。

混淆文件引入

groovy 复制代码
android {
    ...
}

proguard {
   configurations {
      release {
         defaultConfiguration 'proguard-android-optimize.txt'
         configuration 'proguard-project.txt'
         //或者
         // configuration 'proguard-rules.pro'
      }
   }
}

这里将开头提到的问题进行解决。只需要在proguard-rules.pro进行如下写法即可

shell 复制代码
-keep class !androidx.core.**{ *;}

另外上述文件的R8编译器的压缩功能不能使用了,会导致apk变大,这里可以使用proguard自带的压缩功能。这里本文暂未记录

三、R8与proguard

现在Android Studio默认使用R8进行程序编译和优化,proguard进行混淆保护。proguard自身也有缩减优化功能,但是R8编译器和该功能冲突,所以在使用R8编译器的时候,proguard的缩减优化功能无法生效。

四、参考链接

  1. guardsquare
  2. 缩减、混淆处理和优化应用
相关推荐
2501_9159184129 分钟前
iOS 混淆与 IPA 加固一页式行动手册(多工具组合实战 源码成品运维闭环)
android·运维·ios·小程序·uni-app·iphone·webview
不吃凉粉8 小时前
Android Studio USB串口通信
android·ide·android studio
zhangphil8 小时前
android studio设置大内存,提升编译速度
android·android studio
编程乐学10 小时前
安卓非原创--基于Android Studio 实现的天气预报App
android·ide·android studio·课程设计·大作业·天气预报·安卓大作业
大熊的瓜地11 小时前
Android automotive 框架
android·android car
私人珍藏库12 小时前
[Android] Alarm Clock Pro 11.1.0一款经典简约个性的时钟
android·时钟
消失的旧时光-194314 小时前
ScheduledExecutorService
android·java·开发语言
小糖学代码14 小时前
MySQL:14.mysql connect
android·数据库·mysql·adb
怪兽201416 小时前
请谈谈什么是同步屏障?
android·面试
帅锅锅00717 小时前
SeLinux 全面详解
android·linux