Android Studio利用Gradle删除没有使用到的资源和代码文件

来源:互联网 发布:儿童编程机构 编辑:程序博客网 时间:2024/05/16 06:31

一、打包时忽略无用资源

  我们在打包的时候默认会把没有用到的资源(比如图片)也打包成app,徒增了应用的大小。现在我们可以利用Gradle来优雅的去除没有用到的资源文件了!

就是在gradle中配置shrinkResources true。这个东西依赖于minifyEnabled,所以minifyEnabled也要为true才行。

官方推荐在正式版中这么写:

android {        buildTypes {            release {                minifyEnabled true                shrinkResources true            }        }    }
如果你觉得debug包也太大,可以按照下面的方式写:
buildTypes {        debug {            minifyEnabled true            shrinkResources true        }        release {            minifyEnabled true            shrinkResources true            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }    }
  我通过测试确实可以大大减少应用的大小,但也发现了一个问题,很多没有用到的类还是会被打包进去。比如你用了lib,lib里有很多很多类,你可能就用到了一个类,但却把lib中的所有类都打包了进去,很不合理。而且因为去除无效代码的功能要依赖于混淆,混淆又是一个耗时的操作,还是没有彻底解决打包慢的问题。

 

二、打包时忽略无用的代码

  我目前的需求是很多工具类都在一个lib中,但我平常只用到lib中的几个类,所以希望生成apk的时候自动拍出lib中没有用到的类。于是我想到了下面的办法:

我首先在debug模式下配置一下,在debug时也进行混淆,并且自定义了混淆的配置文件debug-proguard-rules.pro

buildTypes {        debug {            minifyEnabled true // 是否混淆            shrinkResources true // 是否去除无效的资源文件            proguardFiles getDefaultProguardFile('proguard-android.txt'),'debug-proguard-rules.pro'        }        release {            minifyEnabled true // 是否混淆            shrinkResources true // 是否去除无效的资源文件            // 混淆的配置文件            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }    }
这样在debug的时候也会进行混淆,但我仅仅需要混淆lib包中的代码,而不混淆我app项目下的代码。这样就可以删除掉lib中无用的代码了。测试下来可以保证只有用到的东西才会被打包进来,其余的东西都没有被打包,效果不错!

 此外,你混淆的时候也会对你的代码进行优化,比如我写了下面一个判断intent的方法:

    public static boolean isBundleEmpty(Intent intent) {        if (intent != null) {            if (intent.getExtras() == null){                return true;            }        }        return false;    }
混淆后发现它进行了自动优化:
public static boolean a(Intent paramIntent)  {    return (paramIntent == null) && (paramIntent.getExtras() == null);  }
1 0