两分钟将你的Flutter/Android项目升级到AGP 8.+

2,521 阅读1分钟

Flutter/Android项目升级到AGP 8.+

  1. 安装最新版Android Studio使用AGP Upgrade Assistant迁移到AGP 8.0+,全自动更改当前模块,一步到位

  2. 在app模块下 build.gradle 添加 namespace,正常情况下升级助理会自动处理好这一步

    android {
        namespace '你的包名'
        // ...
    }
    
  3. 到android目录下的根 build.gradle 下找到下面的内容,替换成下下面的内容。目的是为了把不兼容AGP 8.+ 的模块手动添加 namesapce,还带一些配置更改,可按需修改成自己需要的

    subprojects {
        project.buildDir = "${rootProject.buildDir}/${project.name}"
    }
    
     subprojects {
         project.buildDir = "${rootProject.buildDir}/${project.name}"
         afterEvaluate {
             if (it.hasProperty('android')) {
                 if (it.android.namespace == null) {
                     def manifest = new XmlSlurper().parse(file(it.android.sourceSets.main.manifest.srcFile))
                     def packageName = manifest.@package.text()
                     println("Setting ${packageName} as android namespace")
                     android.namespace = packageName
                 }
                 def javaVersion = JavaVersion.VERSION_11
                 android {
                     def androidApiVersion = 33
                     def oldJavaVersion = compileOptions.sourceCompatibility
                     def oldAndroidApiVersion = compileSdkVersion
                     compileSdkVersion androidApiVersion
                     defaultConfig {
                         targetSdkVersion androidApiVersion
                     }
                     compileOptions {
                         sourceCompatibility javaVersion
                         targetCompatibility javaVersion
                     }
                     tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
                         kotlinOptions {
                             jvmTarget = javaVersion.toString()
                         }
                     }
                     println("Setting java version from $oldJavaVersion to $javaVersion")
                     println("Setting compileSdkVersion and targetSdkVersion from ${oldAndroidApiVersion.toString().split("-").last()} to $androidApiVersion")
                 }
                 println("========================================")
             }
         }
     }
    
  4. 迁移完成,可以跑了

参考资料: