
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
我们编译鸿蒙hap包的时候,往往希望把当前打包的时间写入鸿蒙应用里面,安卓的的VersionCode,VersionName是在build.gradle中配置,而鸿蒙则是config.json,在json中配置的缺点是不能运行代码。通常android是通过调用一个函数获取当前时间,在BuildConfig中新建一个成员,将时间赋值给当前变量,当然也可以把事件赋值给VersionName。但是鸿蒙却行不通。
本文提供一种将当前构建时间写入versionName的思路,只是起到抛砖引玉的作用,有更好的方案评论区见!
1.我们在模块下的build.gradle中可以定义一个获取当前时间的函数
2.ohos闭包中有个outgoingVariants变量,通过outgoingVariants.configure()或者outgoingVariants.outputs.each()可以执行我们的任务,并且是在编译hap之前执行
3.新建一个任务,读取工程目录下的config.json文件,找到versionName的内容,将步骤1的时间替换掉
/**
* 获取编译时间
*/
String getBuildTime() {
Date date = new Date();
//中国用的是东八区时间,数值上是在UTC时间上加8
//String dateStr = "\"" + date.format("yyyy-MM-dd HH:mm:ss", TimeZone.getTimeZone("UTC")) + "\"";
//String dateStr = date.format("yyyyMMdd.HHmmss");
String dateStr = date.format("yyyy-MM-dd HH:mm:ss");
return dateStr;
}
ohos {
outgoingVariants.outputs.each {}
outgoingVariants.configure {
println("outgoingVariants.configure--->")
String str = ""
File file = new File("${projectDir.path}/src/main/config.json")
println("buildFile.path-2-->,${getBuildTime()}")
try {
Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8")
StringBuilder sb = new StringBuilder()
String line = null;
int flag = 0;
while ((line = reader.readLine()) != null) {
if (line.contains("\"code\"")) {
//println("code-->${line}")
flag = 1;
} else if (line.contains("\"name\"") && flag == 1) {
//println("code-->${line}")
flag = 2;
String[] splits = line.split(":")
String[] splits2 = splits[1].split("\"")
line = splits[0] + ":" + splits2[0] + "\"" + getBuildTime() + "\"";
//println("code-->${line}")
}
sb.append(line).append('\n');
}
reader.close()
str = sb.toString()
//println(str)
} catch (IOException e) {
e.printStackTrace()
}
//write
try {
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file))
writer.write(str)
//writer.flush()
writer.close()
} catch (IOException e) {
e.printStackTrace()
}
}
}
build
编译时,查看我们任务确实先执行了
测试
index.ets
import app from '@system.app';
@Entry
@Component
struct Index {
@State versionName: string = '1.0.0';
@State versionCode: number = 100000;
onPageShow() {
console.log('onPageShow start')
this.versionCode = app.getInfo().versionCode;
this.versionName = app.getInfo().versionName;
console.log('onPageShow end')
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('versionCode:'+this.versionCode.toString())
.fontSize(20)
.fontWeight(FontWeight.Bold)
Text('versionName:'+this.versionName)
.fontSize(20)
.fontWeight(FontWeight.Bold)
}
.width('100%')
.height('100%')
}
}
总体思路:获取当前时间,读取config.json,替换内容让后重新写入