Android studio 自動複製生成的 apk

攻城狮-洪發表於2024-06-13

KTS 指令碼

方式一

// 頂層 build.gradle.kts
val apkBaseName: String = "VoiceAssistant"  
  
allprojects {  
    project.extra.apply {
        set("apkBaseName", apkBaseName)  
    }  
}

// 模組 build.gradle.kts
android {
	applicationVariants.all {  
	    val apkBaseName = project.ext.get("apkBaseName") as String  
	    val moduleName = project.name  
	    val apkName = if (apkBaseName.isNotBlank()) {  
	        "${apkBaseName}_${moduleName}_${versionName}.apk"  
	    } else {  
	        "${moduleName}_${versionName}.apk"  
	    }  
	  
	    if (buildType.name == "release") {  
		    // 也可以用 assembleProvider.configure {
	        assembleProvider.get().doLast {  
		        // 可以這樣過濾 if (name == "assembleRelease") 
				project.copy {  
				    val fromDir = packageApplicationProvider.get().outputDirectory.asFile.get().absolutePath  
				    val outDir = File(project.rootDir, "outputs")  
				  
				    from(fromDir) {  
				        include("**/*.apk")  
				    }  
				    into(outDir)  
				    rename {  
				        println("> Task :copy from ${fromDir} into ${File(outDir, apkName)}")  
				        apkName  
				    }  
				}      
			}    
		}  
	} 
}

方式二

// 模組 build.gradle.kts
// copy apk  
tasks.register<Copy>("copyReleaseApk") {  
    println("> Task :register copyReleaseApk")  
  
    val apkBaseName = project.ext.get("apkBaseName") as String  
    val moduleName = project.name  
    val versionName = android.defaultConfig.versionName  
    val apkName = if (apkBaseName.isNotBlank()) {  
        "${apkBaseName}_${moduleName}_${versionName}.apk"  
    } else {  
        "${moduleName}_${versionName}.apk"  
    }  
  
    val fromDir = File(project.buildDir, "outputs/apk/release")  
    val outDir = File(project.rootDir, "outputs")  
  
    from(fromDir) {  
        include("*.apk")  
    }  
    into(outDir)  
    rename {  
        println("> Task :copy from $fromDir into ${File(outDir, apkName)}")  
        apkName  
    }  
}  
  
tasks.whenTaskAdded {  
    if (name == "assembleRelease") {  
        finalizedBy("copyReleaseApk")  
    }  
}

Gradle

// 模組 build.gradle
android {
    applicationVariants.all { variant ->  
	    // apk 改名
        variant.outputs.all { output ->  
            outputFileName = "Factory" + "-" + buildType.name + "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk"  
        }
            
        variant.assemble.doLast {  
            // 將生成的 APK 複製到 app/release 資料夾  
            File outDir = new File('release')  
            variant.outputs.forEach { file ->  
                copy {  
                    from file.outputFile  
                    into outDir  
                } 
            }
		}
	}
}

相關文章