问题
I have a requirement to set google map Api key dynamically i.e form the code not from manifest .Currently I am getting this value form string.xml . Which is not the preferred way according to the requirement .
<meta-data`android:name="com.google.android.maps.v2.API_KEY"`
android:value="@string/map_api_key"
/>
How can I set this value form code .
回答1:
The way you would do this is as a manifest placeholder.
In your AndroidManifest.xml put a variable declaration like this:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="${mapsApiKey}"/>
then in your build.grade enter this:
android {
defaultConfig {
manifestPlaceholders = [ mapsApiKey:"debugKey"]
}
buildTypes {
release {
manifestPlaceholders = [ mapsApiKey:"prodKey" ]
}
}
}
Documentation is here: http://tools.android.com/tech-docs/new-build-system/user-guide/manifest-merger#TOC-Placeholder-support
Note I'm making assumptions here about your use case. This only applies if you're trying to swap out keys based on build type.
回答2:
You can do something like this:
mMapView = new MapView(this, mapApiKey);
But you cannot both have the widget in your xml layout and set the API key in Java. In this case you will need to dynamically add the map to your layout.
Edit: from api v2, this is not possible, you have to set the api key in the manifest file.
来源:https://stackoverflow.com/questions/32243838/android-how-to-set-google-map-api-key-dynamically-not-from-androidmanifest