Sometimes you have the need to set up some app-wide configuration information in an Android app or need to create a class that can be used in multiple projects with a generic way of setting configuration values. This is particularly useful for things like API keys that will probably be different across apps but should be accessible in the same way. There are several ways to do it, but the one I’ve come to prefer is adding a meta-data node to the AndroidManifest.xml file. If you are familiar with Android Adnetworks, most of them are using meta-data for this.
This field can be used to store a boolean, float, int, or String and is later accessed by the Bundle method for your data type (e.g., getInt()). Here is an example of how to define a value in your AndroidManifest.xml:
Let’s look at an example
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.metadataexample" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.metadataexample.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="myAPIKey" android:value="sample_value" /> </application> </manifest>
To get the value in the java code.
String TAG = "Example Meta-Data"; try { ApplicationInfo ai = getPackageManager().getApplicationInfo( getPackageName(), PackageManager.GET_META_DATA); Bundle bundle = ai.metaData; String myAPIKey = bundle.getString("myAPIKey"); System.out.println("API KEY : " + myAPIKey); } catch (NameNotFoundException e) { Log.e(TAG, "Failed to load meta-data, NameNotFound: " + e.getMessage()); } catch (NullPointerException e) { Log.e(TAG, "Failed to load meta-data, NullPointer: " + e.getMessage()); }
You can download the sample code from here.