android 基于Gradle 混淆jar包

时间:2022-05-31 09:06:28

大家都知道,混淆apk,配置如下,编译工具会给我们自动混淆

 混淆代码:
1 先到工程目录下,找到project.properties 这个文件
2 根据提示找到proguard-android.txt 这个文件
3 将这个文件拷贝回工程目录。
4 将project.properties这个文件里面的 proguard.config=proguard-android.txt

但是如果混淆的时候需要保存哪些类文件不混淆。只要在proguard-android.txt 添加一些配置就好了,具体本文本次就不做介绍。


亲试有效:这是build.gradle 的代码

apply plugin: 'android-library'

dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
compile project(':sogou-volley')
}

android {
compileSdkVersion 21
buildToolsVersion "23.0.3"

sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
jniLibs.srcDirs = ['libs']
}

// Move the tests to tests/java, tests/res, etc...
instrumentTest.setRoot('tests')

// Move the build types to build-types/<type>
// For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
// This moves them out of them default location under src/<type>/... which would
// conflict with src/ being used by the main source set.
// Adding new build types or product flavors should be accompanied
// by a similar customization.
debug.setRoot('build-types/debug')
release.setRoot('build-types/release')
}
}
task makeJar(dependsOn: ['compileReleaseJavaWithJavac'], type: Jar) {

//需打包的资源所在的路径集
def srcClassDir = [project.buildDir.absolutePath + "/intermediates/classes/release"];

//初始化资源路径集
from srcClassDir
println "lixiang-->>"+srcClassDir

//去除路径集下部分的资源
exclude "com/sogou/gamecenter/sdk/BuildConfig.class"
//这里需要改为自己的包名,我的包名是,com.sogou.gamecenter.sdk。所以就写为了com/sogou/gamecenter/sdk/
exclude "com/sogou/gamecenter/sdk/BuildConfig\$*.class"
exclude "**/R.class"
exclude "**/R\$*.class"
//只导入资源路径集下的部分资源
include "com/sogou/gamecenter/sdk/**/*.class"

//整理输出的 Jar 文件后缀名
extension = "jar"
//最终的 Jar 文件名......如果没设置,默认为 [baseName]-[appendix]-[version]-[classifier].[extension]
archiveName = "lxcaySDKLib.jar"
}

task proguardJar(dependsOn: ['makeJar'], type: proguard.gradle.ProGuardTask) {

//混淆的配置文件,我的是叫 proguard.cfg,也许有人叫 proguard-project.txt
configuration 'proguard.cfg'
String inJar = makeJar.archivePath.getAbsolutePath()
//输入 jar
injars inJar
println "lixiang->>"+inJar
//输出 jar
String outJar = inJar.substring(0, inJar.lastIndexOf(File.separator)) + "/proguard-${makeJar.archiveName}"
outjars outJar
println "lixiang->>"+outJar
//设置不删除未引用的资源(类,方法等)
dontshrink
}

//直接敲,gradlew 会打印所有的task
//gradle haha命令 ,就可以打印出 haha 来。
//task haha {
// println "haha"
//}

//task hello << {
// println "hello world"
//}
// 这2个是等价的。
//task hello {
// doLast{
// println "hello world"
// }
//}

这是proguard-android.txt的代码


#
# This ProGuard configuration file illustrates how to process Android
# applications.
# If you're using the Android SDK, the Ant release build and Eclipse export
# already take care of the proper settings. You only need to enable ProGuard
# by commenting in the corresponding line in project.properties. You can still
# add project-specific configuration in proguard-project.txt.
#
# This configuration file is for custom, stand-alone builds.

# Specify the input jars, output jars, and library jars.
# Note that ProGuard works with Java bytecode (.class),
# before the dex compiler converts it into Dalvik code (.dex).


#细节1. ../是代表了我的 项目结构的路径。

#细节2.这里需要引用到一些android自己的jar,比如这个 android.jar,现在在我工程的libs下面是没有的,于是我在我的过程里面创建了一个临时的文件夹,lib。把android.jar 放到了里面。
-libraryjars ../lib/android.jar

-libraryjars ../SogouGameSDK/libs/android-support-v13.jar
-libraryjars ../SogouGameSDK/libs/alipaySdk-20160825.jar
-libraryjars ../SogouGameSDK/libs/gamecat-sdk3.03.jar
-libraryjars ../SogouGameSDK/libs/gamecatsdk_1.0.0.jar
-libraryjars ../SogouGameSDK/libs/gson-2.2.2.jar
-libraryjars ../SogouGameSDK/libs/ipaynow_onlywechat_v2.0.0.jar
-libraryjars ../SogouGameSDK/libs/mta-sdk-1.6.2.jar
-libraryjars ../SogouGameSDK/libs/open_sdk_v2.9.1.jar
-libraryjars ../SogouGameSDK/libs/passportsdk.jar
-libraryjars ../SogouGameSDK/libs/PYWSDK.jar
-libraryjars ../SogouGameSDK/libs/sogou-volley.jar
-libraryjars ../SogouGameSDK/libs/sun.misc.BASE64Decoder.jar
-libraryjars ../SogouGameSDK/libs/TenpayServiceSDK_V5.0.jar
-libraryjars ../SogouGameSDK/libs/UPPayAssistEx.jar
-libraryjars ../SogouGameSDK/libs/UPPayPluginEx.jar



#-libraryjars /usr/local/android-sdk/add-ons/google_apis-7_r01/libs/maps.jar
# ...
# Preverification is irrelevant for the dex compiler and the Dalvik VM.

-dontpreverify

# Reduce the size of the output some more.

-allowaccessmodification

# Switch off some optimizations that trip older versions of the Dalvik VM.

-optimizations !code/simplification/arithmetic

# Keep a fixed source file attribute and all line number tables to get line
# numbers in the stack traces.
# You can comment this out if you're not interested in stack traces.

-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable

# RemoteViews might need annotations.

-keepattributes *Annotation*

# Preserve all fundamental application classes.

-keep public class * extends android.app.Dialog
-keep public class * extends android.view.ViewGroup
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class com.google.vending.licensing.ILicensingService
-keep public class com.android.vending.licensing.ILicensingService
#保留volley 不被混淆
-keep class com.android.volley.** {*;}
-keep class com.sogou.wan.** {*;}
-keep class com.android.volley.toolbox.** {*;}
-keep class com.android.volley.Response$* { *; }
-keep class com.android.volley.Request$* { *; }
-keep class com.android.volley.RequestQueue$* { *; }
-keep class com.android.volley.toolbox.HurlStack$* { *; }
-keep class com.android.volley.toolbox.ImageLoader$* { *; }

#忽略警告
-dontwarn com.google.gson.**
-dontwarn com.google.gson.internal.**
-dontwarn com.unionpay.mobile.android.**
-dontwarn com.sina.weibo.sdk.widget.**
-dontwarn com.ut.device.**
-dontwarn com.ta.utdid2.**
-dontwarn com.alipay.**
-dontwarn com.unionpay.**
-dontwarn android.support.**

-dontwarn com.hdsdk.**
-dontwarn com.gamecat.pay.**
-dontwarn com.ipaynow.wechatpay.plugin.**
-dontwarn com.tencent.**
-dontwarn com.sogou.passportsdk.**
-dontwarn com.sogou.upd.alex.**
-dontwarn com.pengyouwan.**
-dontwarn com.android.volley.**
-dontwarn com.sogou.wan.common.**
-dontwarn Decoder.**
-dontwarn com.UCMobile.PayPlugin.**
#这是proguardjar混淆编译不过,添加这句 “忽略警告” 就编译通过了;
-dontwarn com.sogou.gamecenter.sdk.views.RatioLayout

##忽略警告,经过试验,发现 ignorewarnings,相当于上面一片的 -dontwarn
#-ignorewarnings

#保证是独立的jar,没有任何项目引用,如果不写就会认为我们所有的代码是无用的,从而把所有的代码压缩掉,导出一个空的jar
-dontshrink

##先keep再忽略。不可以加public
-keep class com.sogou.gamecenter.sdk.views.RatioLayout{
*;
}

# Preserve all View implementations, their special context constructors, and
# their setters.

-keepclassmembers public class * extends android.view.View {
public <init>(android.content.Context);
public <init>(android.content.Context, android.util.AttributeSet);
public <init>(android.content.Context, android.util.AttributeSet, int);
void set*(***);
*** get*();
}
#忽略自定义view

-keepattributes Signature #忽略泛型
-keepattributes Exceptions,InnerClasses #忽略异常和内部类

# Preserve all classes that have special context constructors, and the
# constructors themselves.

-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}

# Preserve all classes that have special context constructors, and the
# constructors themselves.

#如果拥有某成员,保留类和类成员
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}

# Preserve all possible onClick handlers.

-keepclassmembers class * extends android.content.Context {
public void *(android.view.View);
public void *(android.view.MenuItem);
}

# 保存所有 Parcelable 的实现
-keepclassmembers class * implements android.os.Parcelable {
static android.os.Parcelable$Creator CREATOR;
}

# 保存所有枚举的实现
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}

# Preserve static fields of inner classes of R classes that might be accessed
# through introspection.

-keepclassmembers class **.R$* {
public static <fields>;
}

# Preserve annotated Javascript interface methods.

-keepclassmembers class * {
@android.webkit.JavascriptInterface <methods>;
}

#这样是keep所有类的所有静态变量。
-keepclassmembers class ** {
static <fields>;
}

-keep class android.support.annotation.Keep

-keep @android.support.annotation.Keep class * {*;}

-keepclasseswithmembers class * {
@android.support.annotation.Keep <methods>;
}

-keepclasseswithmembers class * {
@android.support.annotation.Keep <fields>;
}

-keepclasseswithmembers class * {
@android.support.annotation.Keep <init>(...);
}

# Preserve the required interface from the License Verification Library
# (but don't nag the developer if the library is not used at all).

-keep public interface com.android.vending.licensing.ILicensingService

-dontnote com.android.vending.licensing.ILicensingService

# The Android Compatibility library references some classes that may not be
# present in all versions of the API, but we know that's ok.

# Preserve all native method names and the names of their classes.

-keepclasseswithmembernames,includedescriptorclasses class * {
native <methods>;
}

# Preserve the special static methods that are required in all enumeration
# classes.

-keepclassmembers,allowoptimization enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}

# Explicitly preserve all serialization members. The Serializable interface
# is only a marker interface, so it wouldn't save them.
# You can comment this out if your application doesn't use serialization.
# If your code contains serializable classes that have to be backward
# compatible, please refer to the manual.

-keepclassmembers class * implements java.io.Serializable {
static final long serialVersionUID;
static final java.io.ObjectStreamField[] serialPersistentFields;
private void writeObject(java.io.ObjectOutputStream);
private void readObject(java.io.ObjectInputStream);
java.lang.Object writeReplace();
java.lang.Object readResolve();
}

# Your application may contain more items that need to be preserved;
# typically classes that are dynamically created using Class.forName:

# -keep public class mypackage.MyClass
# -keep public interface mypackage.MyInterface
# -keep public class * implements mypackage.MyInterface

-keep class com.sogou.gamecenter.sdk.bean.SogouGameConfig{
public *;
}

-keep class com.sogou.gamecenter.sdk.SogouGamePlatform{
public *;
}

-keep class com.sogou.gamecenter.sdk.bean.UserInfo{
public *;
}

-keep class com.sogou.gamecenter.sdk.service.UserService{
public *;
}

-keep class com.sogou.gamecenter.sdk.util.Logger{*;}
-keep class com.sogou.gamecenter.sdk.views.FloatMenu{*;}
-keep class com.sogou.gamecenter.sdk.views.BonusToast{*;}
-keep class com.sogou.gamecenter.sdk.views.LoadingToast{*;}

#过滤R文件的混淆
-keep class **.R$* {
*;
}

#保留单个类
-keep class com.sogou.gamecenter.sdk.util.GameUtil{
public *;
}

-keep class com.sogou.gamecenter.sdk.util.H5{
public *;
}

#保留一个完成的包

-keep class com.sogou.gamecenter.sdk.listener.** {
*;
}

# If you wish, you can let the optimization step remove Android logging calls.

#-assumenosideeffects class android.util.Log {
# public static boolean isLoggable(java.lang.String, int);
# public static int v(...);
# public static int i(...);
# public static int w(...);
# public static int d(...);
# public static int e(...);
#}

欢迎交流