gpt4 book ai didi

android - 如何在Android中有条件地编译JAR?

转载 作者:行者123 更新时间:2023-12-03 04:48:27 25 4
gpt4 key购买 nike

我正在尝试在Android Studio中进行有条件的构建,可以在其中通过删除多余的库依赖项(如果特定发行版不需要它们)来减少生成的APK的大小。

我有一些代码大致类似于以下内容:

public class MyClass {

/* Static Declarations. */
public static final boolean USE_LIBRARY = false;

public void doSomething() {
// Are we using the library?
if(MyClass.USE_LIBRARY) {
// Do something with the library that we'd define in my build.gradle.
com.some.gradle.library.MyLibrary.doSomethingWithLibrary();
}
else {
// Do something else.
}
}

}

如果我从Gradle依赖项中删除 com.some.gradle.library,则会收到指示无法编译以上代码的编译错误。如您所见,只要 USE_LIBRARY保持为false,我们就永远不需要做任何引用 MyLibrary;甚至在实例化时也没有,因为它没有引用导入;这些仅在运行时被侵犯。

我可能应该注意,实际上, USE_LIBRARY是与应用程序的 BuildConfig.java相关的以编程方式生成的常量。

编译器肯定可以确定此代码可以优化吗?这是我可以解决的某种预处理程序检查吗?

最佳答案

I'm trying to make a conditional build in Android Studio, where I can reduce the size of the generated APK by removing any superfluous library dependencies if they're not needed for a particular distribution.



步骤#1:为该“特定分布”定义产品 flavor 。为了这个答案,我将其称为 foo。您还需要其他发行版本的其他产品口味。

步骤#2:将将这个JAR中的 compile语句更改为 fooCompile语句,因此它将仅用于 foo构建。

步骤#3:在每个产品 flavor 的源集中都有一个 MyClass版本(例如 src/foo/java/),其中 foo中的一个引用库,而其他版本则不。

关于android - 如何在Android中有条件地编译JAR?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43853097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com