Janin
Janin

Reputation: 306

How do I get the resource ID of the app icon in my applicaton from an API

I am writing an API that can be included in various APK's. I want to generate a notification with that app's icon, which requires the resource ID. I'm not finding a way to find the resource ID. I don't know the name of the app's icon. Context is passed in to my class in the constructor. Here is what I have so far:

        ApplicationInfo app = mContext.getApplicationInfo();
        packageManager = mContext.getPackageManager();

        Drawable drawable = packageManager.getApplicationIcon(app);
        String packageName = packageManager.getApplicationLabel(app);

        // logical next step, but I don't know the name of the drawable
        int appIconId = mContext.getResources().getIdentifier("???", "drawable", packageName);

Thank you!

Upvotes: 8

Views: 11707

Answers (4)

Kartik Agarwal
Kartik Agarwal

Reputation: 1403

As of 2023 this code works perfectly

  var packageName = "com.example.app"   //or any other applicationId
  val iconDrawable = packageManager.getApplicationIcon( packageName );
  binding.imageView.setImageDrawable(iconDrawable)

Upvotes: 0

ByteSlinger
ByteSlinger

Reputation: 1597

Perhaps the API has changed since this question was asked, but I don't think it is necessary to use the PackageManager or the Resources object. Since you already have the context object, you can get the resource id of the app icon directly from the ApplicationInfo, like this:

int appIconResourceId = context.getApplicationInfo().icon;

I get the app icon resource id like this for notifications and also to set icons in my DocumentsProvider extends classes (Storage Access Framework).

Upvotes: 5

android developer
android developer

Reputation: 116392

This method should work for getting the app icon of ANY application, including yours:

String packageName=...; //use getPackageName() in case you wish to use yours
final PackageManager pm=getPackageManager();
final ApplicationInfo applicationInfo=pm.getApplicationInfo(packageName,PackageManager.GET_META_DATA);
final Resources resources=pm.getResourcesForApplication(applicationInfo);
final int appIconResId=applicationInfo.icon;
final Bitmap appIconBitmap=BitmapFactory.decodeResource(resources,appIconResId);

Upvotes: 13

Zsombor Erdődy-Nagy
Zsombor Erdődy-Nagy

Reputation: 16914

I'm afraid that this information needs to be injected into your code by the caller. For example, it could be passed in as an integer parameter along with the Context when calling the appropriate constructor / initialization method.

At least this would also mean that your user has grater control over the appearance of the notifications of your component - I'd consider this a good thing.

Upvotes: 0

Related Questions