文章转自:http://blog.csdn.net/hp910315/article/details/52488474
一、自定义BuildConfig字段
在gradle配置文件中,定义LOG字段,默认为true
buildConfigField "boolean", "LOG", "true"
同步一下工程,查看app/build/generated/source/BuildConfig/Build Varients/package name/BuildConfig 文件。
可以看到自动添加了一个LOG字段
// Fields from default config.
public static final boolean LOG = true;
这样我们就可以在工程中Log中使用这个开关了
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
public static final boolean DEBUG = BuildConfig.LOG;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (DEBUG) {
Log.d(TAG, "hello world!");
}
}
}
具体配置如下:
android {
compileSdkVersion 24
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "test.hpp.cn.testcase"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
buildConfigField("boolean", "LOG", "true")
}
buildTypes {
release {
minifyEnabled false
buildConfigField("boolean", "LOG", "false")
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
上面我们可以看到,默认配置defaultConfig中LOG字段设置为true,在release版本中,Log自动设置为false。并且我们也可以根据自己的需要进行配置。
二、使用Proguard配置文件
默认的Proguard配置文件在$ANDROID_HOME\sdk\tools\proguard 目录下。
1. proguard-android.txt 默认的Proguard配置文件(未优化)
2. proguard-android-optimize.txt 默认的Proguard配置文件(已优化)
3. proguard-project.txt 默认的用户定制Proguard配置文件。
在gradle中配置如下:
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
另外,在proguard-rules.pro文件中,添加我们的优化项,也就是去掉Log。
-assumenosideeffects class android.util.Log{
public static *** v(...);
public static *** i(...);
public static *** d(...);
public static *** w(...);
public static *** e(...);
}
这样在打包release包的时候就可以移除所有的Log,我们也不需要加开关了。
参考文章:
GRADLE自定义你的BUILDCONFIG