Android Gradle Read App Name from strings.xml

后端 未结 3 888
醉话见心
醉话见心 2021-01-17 17:29

I am trying to rename my APK files for each build variant to include the application name, versionName, versionCode and build number when present. So far I have everything w

相关标签:
3条回答
  • 2021-01-17 18:10

    I don't think this can be done easily. Resource resolution is done on the mobile device to accommodate for things like screen orientation, localization and so on. The Gradle build system has no way of knowing which locale to use for example. If you insist on getting the value from the resources, you can open the specific strings.xml file you'd like to use, parse the XML and get the value yourself. In my opinion this is a huge overkill and would be pretty slow and ugly.

    App name is not changed often, so I would be comfortable with having it hardcoded (especially since the apk file name is not visible to the end user, so even if mistakes happen, the impact would be minimal). If you are working on a white label application and have to support dynamic app name, extracting the value to the gradle.properties file (or some other type of configuration file, you are using) should be a better option rather than using the app's resources.

    0 讨论(0)
  • 2021-01-17 18:13

    I don't see any method in Android Plugin docs for accessing resources, so here is the code you can use to find your app's name by searching resources:

    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()
    }
    

    BUT I completely agree with @Samuil Yanovski in that it is not worth it - better hardcode a string. I don't think it will slow down building process, but it is just unnecessary.

    0 讨论(0)
  • 2021-01-17 18:20

    I have create method using @Yaroslav's answer (https://stackoverflow.com/a/37432654/6711554).

    def getApplicationName() {
      try {
         def stringsFile = file("./src/main/res/values/string.xml")
         return new XmlParser().parse(stringsFile).string.find { it.@name.equals 'your_app_name' }.text()
      }catch(e){
         println(e)
         return "Default App Name"
      }
    }
    

    You can read any string in your gradle from your any resource file.

    0 讨论(0)
提交回复
热议问题