Wednesday, 29 April 2015

HB Blog 70: Metadata In Android Manifest.

A name-value pair for an item of additional, arbitrary data that can be supplied to the parent component. A component element can contain any number of <meta-data> subelements. The values from all of them are collected in a single Bundle object and made available to the component as the PackageItemInfo.metaData field.
It is mostly used to store 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.

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.

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File
Have a look on few code snippets, 
AndroidManifest.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.metadata_as" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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="hbdata" android:value="@string/app_name"></meta-data>
    </application>

</manifest> 
 
 
 
MainActivity.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getMetadataValue();
    }

    private void getMetadataValue(){
        try {
            ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            Bundle bundle = ai.metaData;
            String metadataValue = bundle.getString("hbdata");
            System.out.println("API KEY : " + metadataValue);
        } catch (Exception e){
            System.out.println("Exception "+e.getMessage());
        }
    }
}

No comments:

Post a Comment