ste*_*113 10 groovy android build gradle android-gradle-plugin
我正在尝试为每个构建变体重命名我的APK文件,以包含应用程序名称,versionName,versionCode和内部版本号.到目前为止,除了应用程序名称之外,我的所有工
我想使用AndroidManifest.xml文件用于android:label 的相同值.这来自字符串资源@string/app_name.我已经看到了使用以下方法替换资源值的能力:
resValue "string", "app_name", "Some new value"
Run Code Online (Sandbox Code Playgroud)
但我只想读取此值并使用它来命名我的APK文件.
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
renameApk(variant, output)
}
}
def renameApk(variant, output) {
def apkPath = output.outputFile.parent
def baseName = project.archivesBaseName
baseName += "-${variant.buildType.name}"
// add version name and version code
baseName += "-v${variant.mergedFlavor.versionName}-${variant.mergedFlavor.versionCode}"
// if built on jenkins ci, add jenkins build number:
def buildNumber = System.getenv('BUILD_NUMBER')
if (buildNumber && buildNumber.size() > 0) {
baseName += "-b${buildNumber}"
}
// if the variant will not be zipAligned, specify that
if (!output.zipAlign) {
baseName += '-unaligned'
}
// set the output file
output.outputFile = new File(apkPath, "${baseName}.apk");
}
Run Code Online (Sandbox Code Playgroud)
我没有在Android插件文档中看到任何用于访问资源的方法,因此以下是您可以通过搜索资源来查找应用名称的代码:
def getAppName() {
def stringsFile = android.sourceSets.main.res.sourceFiles.find { it.name.equals 'strings.xml' }
return new XmlParser().parse(stringsFile).string.find { it.@name.equals 'app_name' }.text()
}
Run Code Online (Sandbox Code Playgroud)
但我完全赞同@Samuil Yanovski,因为它不值得 - 更好地硬编码字符串.我不认为这会减慢建筑过程,但这是不必要的.
我认为这并不容易做到。资源解析是在移动设备上完成的,以适应屏幕方向、本地化等问题。例如,Gradle 构建系统无法知道要使用哪个区域设置。如果您坚持要从资源中获取值,则可以打开要使用的特定 strings.xml 文件,解析 XML 并自行获取值。在我看来,这是一个巨大的杀伤力,并且会非常缓慢且丑陋。
应用程序名称不会经常更改,因此我很乐意将其硬编码(特别是因为最终用户看不到 apk 文件名,因此即使发生错误,影响也很小)。如果您正在开发白标签应用程序并且必须支持动态应用程序名称,则将值提取到 gradle.properties 文件(或您正在使用的其他类型的配置文件)应该是一个更好的选择,而不是使用应用程序的资源。
| 归档时间: |
|
| 查看次数: |
3173 次 |
| 最近记录: |