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

Viewed 9753

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!

3 Answers

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);

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.

Related