Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import android.content.Context;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;

import android.graphics.drawable.Drawable;

import android.os.Build;

import android.util.DisplayMetrics;

public class Main {
    public static Drawable getIconFromPackageName(String packageName, Context context) {
        PackageManager pm = context.getPackageManager();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
            try {
                PackageInfo pi = pm.getPackageInfo(packageName, 0);
                Context otherAppCtx = context.createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY);

                int displayMetrics[] = { DisplayMetrics.DENSITY_XXXHIGH, DisplayMetrics.DENSITY_XXHIGH,
                        DisplayMetrics.DENSITY_XHIGH, DisplayMetrics.DENSITY_HIGH, DisplayMetrics.DENSITY_MEDIUM,
                        DisplayMetrics.DENSITY_TV };

                for (int displayMetric : displayMetrics) {
                    try {
                        Drawable d = otherAppCtx.getResources().getDrawableForDensity(pi.applicationInfo.icon,
                                displayMetric);
                        if (d != null) {

                            return d;
                        }
                    } catch (Resources.NotFoundException e) {
                    }
                }

            } catch (Exception e) {
                // Handle Error here
            }
        }

        ApplicationInfo appInfo = null;
        try {
            appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            return null;
        }

        return appInfo.loadIcon(pm);
    }

    public static PackageInfo getPackageInfo(String path, Context context) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pi = pm.getPackageArchiveInfo(path, 0);

        pi.applicationInfo.sourceDir = path;
        pi.applicationInfo.publicSourceDir = path;
        return pi;
    }
}