question
Recently, there is a requirement in the Cordova project, where you need to read files from the assets directory, load configuration information, and use it in the code. Because I saw that something similar was written in gradle, I read it using gradle, and then used BuildConfig to save it. I think this is very good to use, so I will share it.
describe
In the Cordova project, the front-end page will be packaged into the www folder in the assets directory, where you need to read the information domain name information from this folder.
assets/www/
_domain_ = 'xxx';
gradle read operation
I originally wanted to try it with R, but later I thought it was not feasible. Next, use gradle to solve the problem. In the Android closure in the gradle file, define a variable DOMAIN and write a function to get it.
android {
//Other codes
def DOMAIN = getDomainFromIndexHtml()
}
The function is written outside the Android closure:
String getDomainFromIndexHtml() { //Get the environment from it String envContent = getFileContent( + "/assets/www/"); envContent = (" ", ""); String reg = "_domain_=(.*?);" Pattern corPattern = (reg); Matcher corMatcher = (envContent); (); String result = (0) result = ("_domain_=", "").replace("\"", "").replace("\'", "\"").replace(";", ""); return result; } String getFileContent(String path) { File file = new File(path); byte[] buffer = new byte[()]; FileInputStream fileInputStream = new FileInputStream(file); (buffer); (); String content = new String(buffer, "UTF-8"); return content; }
BuildConfig Configuration
Write the above code and run this code when compiling the Android project, and you can get the domain name. If the read domain name is written into BuildConfig, it is actually saved after compilation and does not need to read the file at runtime, which can improve the operation efficiency of the application.
Or find the buildTypes closure in the android closure, add buildConfigField into debug and release, and then you can configure the BuildConfig variable. The syntax is very simple.
android {
//Other codes
def DOMAIN = getDomainFromIndexHtml()
buildTypes {
release {
//Other codes
buildConfigField("String", "DOMAIN", "${DOMAIN}")
}
debug {
//Other codes
buildConfigField("String", "DOMAIN", "${DOMAIN}")
}
}
}
Used in the code
After configuring BuildConfig, it is best to rebuild it. In Build -> Rebuild Project, use it as follows in the code:
String domain = ;
This is the article about the detailed explanation of Android's process of using gradle to read and save data to BuildConfg. For more related Android BuildConfg content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!