Programmatically extract background color from theme

With Android sometimes we need to get the background color of current them programmatically. There have been StackOverflow questions on this here and here but they didn't help me. Later on I found a satisfactory answer from my coworker and wanted to document this here. This solution has been tested on Samsung Galaxy S4 running Android 4.2.2 but should work on all Android devices running 2.3.x and later.

You may have a custom theme defined in your themes.xml file.

<style name="Theme.customTheme" parent="Theme.AppCompat">  
    <item name="bckgrnd">@style/custom_bckgrnd</item>
    <item name="frontImg">@style/front_img</item>
    <item name="topImg">@style/top_img</item>

And in your styles.xml you will have:

    <style name="custom_bckgrnd">
        <item name="android:background">#00c1cc</item>

Now you can set up this theme for use in AndroidManifest file with android:theme="@style/Theme.customTheme" line on an <activity> or <application> tag. This sets up the xml for use.

To programmatically extract this themes color in any activity, the following code is typically added to an activity's onCreate() method:

    int[] attrs = {android.R.attr.background};
    TypedValue tv = new TypedValue();
    getTheme().resolveAttribute(R.attr.bckgrnd, tv, true);
    TypedArray ta = obtainStyledAttributes(tv.resourceId, attrs);
    int color = ta.getColor(0, Color.WHITE);

Now color has the theme's background color and can be used as needed in the activity.