BuildConfig没有正确创建(Gradle Android)

107

我正在尝试将我们的Android应用程序转换为gradle构建。 我已经成功构建了项目及其库。 现在,我正在尝试为我们的各种环境(开发/测试/生产)创建单独的apk文件,因为它们消耗restful服务的URL不同。

在搜索中,我认为最好的方法是为每个环境创建不同的BuildConfig。这是我尝试的方法:

import java.util.regex.Pattern

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:+'
    }
}

apply plugin: 'android'

task('increaseVersionCode') << {
    def manifestFile = file("AndroidManifest.xml")
    def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
    def manifestText = manifestFile.getText()
    def matcher = pattern.matcher(manifestText)
    matcher.find()
    def versionCode = Integer.parseInt(matcher.group(1))
    def manifestContent = matcher.replaceAll("versionCode=\"" + ++versionCode + "\"")
    manifestFile.write(manifestContent)
}

tasks.whenTaskAdded { task ->
    if (task.name == 'generateReleaseBuildConfig') {
        task.dependsOn 'increaseVersionCode'
    }
}

dependencies {
    compile 'com.android.support:support-v4:19.0.0' 
    compile files('libs/commons-io-2.4.jar',
                  'libs/google-play-services.jar',
                  'libs/gson-2.2.4.jar',
                  'libs/universal-image-loader-1.8.6.jar',
                  'libs/wakeful-1.0.1.jar')
    compile project(':pulltorefresh_lib')
    compile project(':edgeeffect_lib')
    compile project(':viewpagerindicator_lib')        
}

android {
    buildToolsVersion "18.1.1"
    compileSdkVersion "Google Inc.:Google APIs:18"

    defaultConfig { 
       minSdkVersion 14
       targetSdkVersion 18
    }

    buildTypes {
        debug {
            packageNameSuffix ".debug"
        }
        dev.initWith(buildTypes.debug)
        dev {
            buildConfigField "String", "URL_SEARCH", "\"https://dev-search.example.com\";"
            buildConfigField "String", "URL_CONNECT", "\"https://dev-connect.example.com\";"
            buildConfigField "String", "URL_SVC_NEWSLIST", "\"https://dev-mobilenews.example.com/newslist\";"
            buildConfigField "String", "URL_SVC_NEWSDETAIL", "\"https://dev-mobilenews.example.com/newsdetail\";"
            buildConfigField "String", "URL_SVC_REGISTERENDPOINTS", "\"https://dev-mobilenews.example.com/registerendpoints\";"
        }
        prod.initWith(buildTypes.release)
        prod {
            buildConfigField "String", "URL_SEARCH", "\"https://search.example.com\";"
            buildConfigField "String", "URL_CONNECT", "\"https://connect.example.com\";"
            buildConfigField "String", "URL_SVC_NEWSLIST", "\"https://mobilenews.example.com/newslist\";"
            buildConfigField "String", "URL_SVC_NEWSDETAIL", "\"https://mobilenews.example.com/newsdetail\";"
            buildConfigField "String", "URL_SVC_REGISTERENDPOINTS", "\"https://mobilenews.pdc-np-cf.lmig.com/registerendpoints\";"          
        }
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
    }
}

问题在于我的BuildConfig.java似乎没有注入静态变量,因此我会遇到类似以下错误的错误:

/Users/path/to/project/MainActivity.java:348: error: cannot find symbol
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.URL_SEARCH)));
                                                                              ^
  symbol:   variable URL_SEARCH
  location: class BuildConfig
/Users/path/to/project/MainActivity.java:359: error: cannot find symbol
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.URL_CONNECT)));
                                                                              ^
  symbol:   variable URL_CONNECT
  location: class BuildConfig
/Users/path/to/project/MainActivity.java:600: error: cannot find symbol
            HttpPost httpPost = new HttpPost(BuildConfig.URL_SVC_REGISTERENDPOINTS);
                                                        ^
  symbol:   variable URL_SVC_REGISTERENDPOINTS
  location: class BuildConfig
/Users/path/to/project/service/AlarmNotificationService.java:145: error: cannot find symbol
        String requestUrl = BuildConfig.URL_SVC_NEWSLIST + "?"
                                       ^
  symbol:   variable URL_SVC_NEWSLIST
  location: class BuildConfig
/Users/path/to/project/service/NewsService.java:240: error: cannot find symbol
        String requestUrl = BuildConfig.URL_SVC_NEWSLIST + "?"
                                       ^
  symbol:   variable URL_SVC_NEWSLIST
  location: class BuildConfig
/Users/path/to/project/service/NewsService.java:530: error: cannot find symbol
            HttpPost httpPost = new HttpPost(BuildConfig.URL_SVC_NEWSDETAIL);
                                                        ^
  symbol:   variable URL_SVC_NEWSDETAIL
  location: class BuildConfig
6 errors

我的构建/源代码/构建配置/调试/com/.../BuildConfig.java 文件包含:

/**
 * Automatically generated file. DO NOT MODIFY
 */
package com....;

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String PACKAGE_NAME = "com.....debug";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 5;
}

我做错了什么?


可能最好删除那些自由软件的参考。虽然这里没有任何关键代码,但最好避免在StackOverflow上共享专有代码 ;) - antonpug
Gradle的BuildConfigField(BuildConfig)无法解析符号。 - Michael
Gradle buildConfigField无法解析符号"BuildConfig"。 - Muhammad Noman
21个回答

4
如果您正在修改环境变量,但在Android Studio中未正确反映,请尝试执行以下操作:
Build -> Clean Project 
File -> Invalidate Caches/Restart... -> Invalidate and Restart 

4

针对 Android Studio 版本

Android Studio Dolphin | 2021.3.1 补丁 1

构建 #AI-213.7172.25.2113.9123335,于 2022 年 9 月 30 日构建

运行时版本:11.0.13+0-b1751.21-8125866 aarch64 VM:由 JetBrains s.r.o. 提供的 OpenJDK 64 位服务器 VM。

我想做什么?

我为应用程序模块设置了三个构建变体,我希望每次更改构建变体时,BuildConfig 都会更改,特别是在 build.gradle(app)配置中定义的该变量。

什么没有起作用?

我尝试了所有三种方法,完全没有起作用,无法重新生成我正在更改的构建变体的 BuildConfig:

  1. 尝试使用 File > invalidate cache and restart,以及 Build > Clean ProjectBuild > Rebuild Project
  2. 仅使用 Build > Make Project
  3. 仅使用 File > Sync Project with Gradle Files

有效方法

然后我尝试了一个出人意料的组合,非常有效

  1. 首先,尝试使用 Build > Make Project
  2. 然后使用 File > Sync Project with Gradle Files

我希望这对于我正在使用的特定版本有效,但不确定其他版本的 Android Studio 是否适用。

感谢 @ravi 和 @ibrokhim 部分回答了这个问题。


1
这个也适用于MacBook Air M2上的Android Studio Flamingo | 2022.2.1 Patch 2。已确认! - smnadim21
@smnadim21 很高兴得知解决方案仍然适用于最新版本的Android Studio,太棒了。我建议你以适当的方式编辑答案,这样对其他人也会有帮助。 - Hassan Jamil

4
非常合乎逻辑的答案,如果这不是在撰写中发生的话。
    buildFeatures {
    // The first line should already be in your project!
    compose = true
    buildConfig = true
    }

现在将生成文件,您可以在应用程序和任何地方使用BuildConfig.Debug。


2

尝试了一切之后,切换构建变体并选择构建 > 构建项目 对我有用。


2

请按照以下步骤操作:

步骤 1

File -> Invalidate Caches/Restart... -> Invalidate and Restart 

第二步

Build -> Clean Project

第三步

Build - > Rebuild Project 

1
在project.ext.envConfigFiles数组中,确保将debug设置为您用于开发的正确.env文件。

1
我按照答案中的所有步骤操作,但仍然无法解决问题。最终我通过修改manifest.xml文件中的包名来解决问题,因为该文件尚未更新。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.android">

0

我曾经遇到过类似的问题,与使用 .initWith(someotherbuildtype) 设置构建类型有关,BuildConfig 没有被正确创建。我不得不切换到父构建变体并首先构建它,然后使用父构建进行初始化的构建类型就能正常构建了。


0
在我的情况下,我期望为我的新Gradle模块创建BuildConfig。但是忘记将其添加为app:模块的依赖项。

0
在我的情况下,strings.xml 和产品口味中都有一个字符串字段 resValue "string", "app_name", "MyApp"
我执行了 Invalidate Caches,然后执行了 Rebuild,接着 Android Studio 给出了重复资源的实际错误。
所以,Invalidate caches -> Rebuild -> Remove string resources which were already in buildconfigfield resvalue 对我有效。
我使用的是 Android Studio Bumblebee 2021.1.1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接