javaandroidxmlandroid-studiomapbox-android

How can I use secrets in XML strings in Android Studio


I want to use MapBox in my Android app, as an alternative to Google Maps. The issue is, they require me to use an API key, and my app is up on GitHub, meaning I can't just use it in the code directly, I have to import it using Android secrets.

For this, I have made a file named secrets.properties, and configured it in the Graddle config for this project. And because this file is ignored by git and isn't included in the imports, I've also made local.defaults.properties, which includes default values for otherwise undefined secrets, and which contents I can show you:

MAPBOX_API_KEY=DEFAULT_API_KEY

The DEFAULT_API_KEY is obviously replaced with the actual API key in the secrets.properties file.

Now, I've got a file mapbox_access_token.xml which is located in the strings resource directory, and this is its content:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
    <string name="mapbox_access_token" translatable="false" tools:ignore="UnusedResources">${MAPBOX_API_KEY}</string>
</resources>

The idea is that Android Studio would automatically replace the ${MAPBOX_API_KEY} with the actual API key from the secrets, but it doesn't happen, as I've discovered using a debug LogCat console: Screenshot of the LogCat window

I tried to google the solution to my issue, but without success. I'm lost. Does anybody here know if it even works with the XML string resources, and if so, how am I supposed to invoke the expression in the string value? And if not, what would be your ideal substitute?

Remember, I cannot include the API key in the source code directly, because it would be visible in the GitHub repository.


Solution

  • Does anybody here know if it even works with the XML string resources

    It does not.

    how am I supposed to invoke the expression in the string value?

    That is not an available option, sorry.

    And if not, what would be your ideal substitute?

    I do not know what your criteria are for "ideal". A simple solution is to put your token in a dedicated string resource file (e.g., res/values/tokens.xml) and add that file to your .gitignore. A more powerful solution is to not bake the API key into your app at all — instead, download it from your Web service and apply it at runtime.