Monday, November 28, 2011

Tip: Handling API Keys

If you've ever done work against the Google APIs or some other metered web service you've no doubt come into contact with API keys. These keys usually associate some identity to the product/client using the web service.
A way to manage this is to create string resources for each API key in a resource file called res/values/strings_apikeys.xml. Below is an example of a resource file with API keys for Google Maps and Android Backup service.

Benefits:

  1. Keys can be referenced in other resource files or the AndroidManifest.xml as shown below.
  2. You can setup a key per region using the region qualifiers. Or use any resource qualifiers to have different keys against.

res/values/strings_apikeys.xml

    @string/apikey_google_maps_debug_laptop
    01rg6-jslkjdakljdakldakjldaasdkasjdlaj-NeedARealKey
    01rg6-jkljakljdklajdlas-UseAKeyHere
    01rg6-jlkfsdklfjasfkajs-FakeKey
    AEdPqrEAAAAIu-GetARealBackupKey

Example of Google Maps View using the referenced key. You can then use this template view using the tag in other layouts.
res/layout/mapview.xml



No comments:

Post a Comment