Android自身可以实现代码的混淆功能,Android集成了代码混淆的功能,这些功能在Android SDK的tools有个proguard目录,这个目录下就是提供了Andoid代码的混淆功能,我们只需要在Android项目中进行简单的配置即可。最初的配置文件为proguard.cfg文件,后来adt升级以后,文件改为了proguard-project.txt,所以,这里,我们以两种方式来讲解如何进行代码混淆
方式一、配置文件为proguard.cfg
1、proguard.cfg文件
创建Android项目之后,在Android项目根目录下有个proguard.cfg文件,这个文件中就是描述了Android的混淆配置。
具体如下:
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-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 * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
2、project.properties文件
这个文件是整个项目的环境配置文件,我们只需要在这个文件中指定代码混淆的配置即可。只需要在代码中加入一行配置
proguard.config=proguard.cfg
如下图:
这样就实现了代码的混淆功能
方式二、配置文件为proguard-project.txt
1、proguard-project.txt文件
这个时候,项目生成的是proguard-project.txt
如下代码所示:
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
2、project.properties
在这个文件中需要我们指定sdk的安装路径sdk.dir,然后再指定proguard的配置proguard.config,我自己sdk的目录是E:\android\adt-bundle-windows-x86_64-20131030\sdk,
所以,我在project.properties文件中新增的两项配置是
sdk.dir=E:\android\adt-bundle-windows-x86_64-20131030\sdk
proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
具体如下图所示:
好了,这样就完成了代码混淆的配置
总结:
两种方式都只是通过配置project.properties文件实现代码混淆的。