Is it possible to get another application's primary color like lollipop's recents view
android, android-5.0-lollipop
Solution
You can retrieve the launcher `Intent` for an application using `PackageManager.getLaunchIntentForPackage` and `PackageManager.getActivityInfo` will return the `ActivityInfo` for it.
Once you have that information you can create a new `Theme`, then use the resources from `PackageManager.getResourcesForApplication` to retrieve the attrs needed to find the `colorPrimary` value.
try {
final PackageManager pm = getPackageManager();
// The package name of the app you want to receive resources from
final String appPackageName = ...;
// Retrieve the Resources from the app
final Resources res = pm.getResourcesForApplication(appPackageName);
// Create the attribute set used to get the colorPrimary color
final int[] attrs = new int[] {
/** AppCompat attr */
res.getIdentifier("colorPrimary", "attr", appPackageName),
/** Framework attr */
android.R.attr.colorPrimary
};
// Create a new Theme and apply the style from the launcher Activity
final Theme theme = res.newTheme();
final ComponentName cn = pm.getLaunchIntentForPackage(appPackageName).getComponent();
theme.applyStyle(pm.getActivityInfo(cn, 0).theme, false);
// Obtain the colorPrimary color from the attrs
TypedArray a = theme.obtainStyledAttributes(attrs);
// Do something with the color
final int colorPrimary = a.getColor(0, a.getColor(1, Color.WHITE));
// Make sure you recycle the TypedArray
a.recycle();
a = null;
} catch (final NameNotFoundException e) {
e.printStackTrace();
}
One caveat is that the launcher `Activity` may not contain a `theme` attribute, in which case you may consider using `PackageManager.getApplicationInfo`, but there's no guarantee the `Application` tag contains a `theme` attribute as well.
Here are some examples:
Contacts
Play Music
Gmail
Problem
I found http://developer.android.com/reference/android/app/ActivityManager.html#getRunningTasks(int) to retrieve current application's baseActivity or topActivity. Then I was able to get the Activity's Resources object. However, the api is no longer available to third party applications in Lollipop