When using the Google MapView component in an Android app, you need a Maps API key which matches your app's signature. This is all fine and dandy, and pretty well explained on Google's web site.
However, a side-effect of how this is done means most developers are working with two different signatures on a daily basis: the signature of the debug key, which is autogenerated by the Android SDK, and their "production" signature which they use for publishing their apps to the market. Working with two signatures means you need two different Maps API keys as well, one for debugging and another for releases.
I didn't want to have to hand-edit constants in my code each time I built a release, and couldn't find any hints online on a more elegant solution, so I came up with the following snippet of code. This code will, at run-time, check which key was used to sign the app and then choose between two Maps API keys, based on whether it is a debug key or not.
static final String DEBUG_TAG = "YourApp";
static final String DEBUG_SIG = "...";
static final String DEBUG_KEY = "DEBUG KEY GOES HERE";
static final String RELEASE_KEY = "RELEASE KEY GOES HERE";
static String staticMapsApiKey = null;
public static String getMapsApiKey(Context context) {
if (staticMapsApiKey == null) {
try {
staticMapsApiKey = RELEASE_KEY;
Signature [] sigs = context.getPackageManager()
.getPackageInfo(context.getPackageName(),
PackageManager.GET_SIGNATURES)
.signatures;
for (int i = 0; i < sigs.length; i++) {
MessageDigest sha = MessageDigest.getInstance("SHA-1");
sha.update(sigs[i].toByteArray());
byte [] digest = sha.digest();
String str = "";
for (int di = 0; di < digest.length; di++) {
str += Byte.toString(digest[di])+":";
}
Log.d(DEBUG_TAG, "Got key sig: " + str);
if (str.equals(DEBUG_SIG)) {
Log.d(DEBUG_TAG, "Oh look, a debug signature!");
staticMapsApiKey = DEBUG_KEY;
break;
}
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
return staticMapsApiKey;
}
This code is admittedly rather ugly - a more experienced Java developer would probably write something a bit more elegant. But it gets the job done, once you have filled in all the constants at the top. The DEBUG_KEY and RELEASE_KEY strings should contain the keys you get from Google. The DEBUG_SIG constant can be filled in by running the code in debug mode, and searching the output of "adb logcat" for the "Got key sig: " message.
Hope this helps someone, and if anyone knows of a more elegant solution, please let me know!
Update: Sure enough, someone came up with a more elegant solution, based on this one. Cool! :-)