Android Question How to get another application's primary color?

jtare

Active Member
Licensed User
Longtime User
I was reading this tread http://stackoverflow.com/questions/...lications-primary-color-like-lollipops-recent on how to get another application primary color but I could not find the way to make it work in B4A.
Can someone help me to understand the answer given in the stackoverflow thread please.
I tried copy the exact java code and paste it in b4a with the #if java tool, but I only got errors, also tried with the reflector library but I just don't know how to translate the code.
The reason why I need the color primary value of a installed app in the phone is to complement this thread (link)(Use it as a background color basically).
Thanks.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
I don't think that it will be very useful. Here:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Dim jo As JavaObject
   jo.InitializeContext
   jo.RunMethod("test", Array("b4a.example"))
End Sub

#if Java
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.Resources.Theme;
import android.graphics.Color;
   public void test(String packageName) {
      try {
      final PackageManager pm = getPackageManager();

      // The package name of the app you want to receive resources from
      final String appPackageName = packageName;
      // 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));
         BA.Log("colorPrimary: " + colorPrimary);
      // Make sure you recycle the TypedArray
      a.recycle();
      a = null;
      } catch (final NameNotFoundException e) {
      e.printStackTrace();
      }
   }
#End If
 
Upvote 0

jtare

Active Member
Licensed User
Longtime User
Thanks Erel, you were right is not very useful, I tried and is not stable it only work with a few apps, for the rest I get wrong colors or no color at all.
 
Upvote 0
Top