Android how to set Google Map Api Key dynamically not from AndroidManifest

风格不统一 提交于 2019-12-12 03:38:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!