简体   繁体   English

如何避免在Android(或任何Java)项目中包含未使用的库?

[英]How to avoid including unused library in Android (or any Java) project?

My project uses 2 third party libraries (both more than 10 MB in size) for some speech processing features. 我的项目使用2个第三方库(大小都超过10 MB)来实现某些语音处理功能。 I need only one of them at a time (almost like a plugin ), a decision I make during build time. 我一次只需要其中一个(几乎像plugin一样 ),这是我在构建时做出的决定。 I have consumed methods of both libraries in the same module as of now. 到目前为止,我已经在同一个模块中使用了这两个库的方法。 My build.gradle has flags like these : 我的build.gradle有这样的标志:

buildConfigField "boolean", "USE_LIB_ONE", "true" buildConfigField“ boolean”,“ USE_LIB_ONE”,“ true”
buildConfigField "boolean", "USE_LIB_TWO", "false" buildConfigField“ boolean”,“ USE_LIB_TWO”,“ false”

In my Java code, I have checks like this : 在我的Java代码中,我进行了如下检查:

if (BuildConfig.USE_LIB_ONE) {
    A.method();
} else if(BuildConfig.USE_LIB_TWO) {
    B.method();
}

My questions are: 我的问题是:

  1. Is there a way to conditionally compile LIBRARY_ONE or LIBRARY_TWO based on buildConfigField? 有没有一种方法可以基于buildConfigField有条件地编译LIBRARY_ONE或LIBRARY_TWO? My APK is getting bulky even when I don't use the other library. 即使我不使用其他库,我的APK也变得越来越庞大。

  2. Is there a cleaner way to design such projects? 有没有更清洁的方式来设计此类项目? My codebase is bloated with if/else checks of the same condition. 我的代码库充斥着相同条件的if / else检查。

  3. I guess gradle product flavors may help in this case, but I don't know a lot about it. 我想在这种情况下,gradle产品的口味可能会有所帮助,但是我对此并不了解。 Can someone please confirm if product flavors do help in conditional compilation? 有人可以确认产品口味是否对条件编译有帮助?

  4. Can ServiceLoader be of any help here? ServiceLoader在这里可以提供任何帮助吗? On a non-Android project I would be possibly using it, but Android implementation sounds buggy based on some SO posts. 在非Android项目中,我可能会使用它,但是基于一些SO帖子,Android实现听起来有问题。

My question is NOT a duplicate of this one . 我的问题不是这个问题的重复。

Currently there is an issue for your question here 目前,您的问题在这里出现

but for a workaround you can use flavor + build type configuration in your build.gradle like this 但是要解决此问题,您可以像这样在build.gradle中使用flavor +构建类型配置

configurations {
  libOneReleaseCompile
  libTwoReleaseCompile
}

dependencies {
    compile 'com.android.support:support-v4:23.1.1'
    compile 'com.android.support:support-annotations:23.1.1'
    compile 'com.android.support:appcompat-v7:23.1.1'

    libOneReleaseCompile 'lib.one.speech'
    libTwoReleaseCompile 'lib.two.speech'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM