Example usage for android.util DisplayMetrics setToDefaults

List of usage examples for android.util DisplayMetrics setToDefaults

Introduction

In this page you can find the example usage for android.util DisplayMetrics setToDefaults.

Prototype

public void setToDefaults() 

Source Link

Usage

From source file:Main.java

/**
 * Because of a BUG of Android (API 13-),
 * get signature info by using "getPackageArchiveInfo" of "PackageManager"
 * always causes "NullPointerException".
 * Lack of code in method "getPackageArchiveInfo":
 *     if ((flags & GET_SIGNATURES) != 0)
 *     {/*from w ww .  ja  v  a  2s .  c  o m*/
 *         packageParser.collectCertificates(pkg, 0);
 *     }
 */
@SuppressWarnings("unchecked")
public static PackageInfo getPackageArchiveInfo(String archiveFilePath, int flags) {
    try {
        Class packageParserClass = Class.forName("android.content.pm.PackageParser");
        Class[] innerClasses = packageParserClass.getDeclaredClasses();
        Class packageParserPackageClass = null;
        for (Class innerClass : innerClasses) {
            if (0 == innerClass.getName().compareTo("android.content.pm.PackageParser$Package")) {
                packageParserPackageClass = innerClass;
                break;
            }
        }
        Constructor packageParserConstructor = packageParserClass.getConstructor(String.class);
        Method parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class,
                String.class, DisplayMetrics.class, int.class);
        Method collectCertificatesMethod = packageParserClass.getDeclaredMethod("collectCertificates",
                packageParserPackageClass, int.class);
        Method generatePackageInfoMethod = packageParserClass.getDeclaredMethod("generatePackageInfo",
                packageParserPackageClass, int[].class, int.class, long.class, long.class);
        packageParserConstructor.setAccessible(true);
        parsePackageMethod.setAccessible(true);
        collectCertificatesMethod.setAccessible(true);
        generatePackageInfoMethod.setAccessible(true);

        Object packageParser = packageParserConstructor.newInstance(archiveFilePath);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        displayMetrics.setToDefaults();

        final File sourceFile = new File(archiveFilePath);

        Object pkg = parsePackageMethod.invoke(packageParser, sourceFile, archiveFilePath, displayMetrics, 0);
        if (pkg == null) {
            return null;
        }

        if ((flags & PackageManager.GET_SIGNATURES) != 0) {
            collectCertificatesMethod.invoke(packageParser, pkg, 0);
        }

        return (PackageInfo) generatePackageInfoMethod.invoke(null, pkg, null, flags, 0, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:Main.java

public static Drawable showUninstallAPKIcon(Context context, String apkPath) {
    String PATH_PackageParser = "android.content.pm.PackageParser";
    String PATH_AssetManager = "android.content.res.AssetManager";
    try {/* w  w  w.  j av a  2  s.  com*/
        Class<?> pkgParserCls = Class.forName(PATH_PackageParser);
        Class<?>[] typeArgs = new Class[1];
        typeArgs[0] = String.class;
        Constructor<?> pkgParserCt = pkgParserCls.getConstructor(typeArgs);
        Object[] valueArgs = new Object[1];
        valueArgs[0] = apkPath;
        Object pkgParser = pkgParserCt.newInstance(valueArgs);
        DisplayMetrics metrics = new DisplayMetrics();
        metrics.setToDefaults();
        typeArgs = new Class[4];
        typeArgs[0] = File.class;
        typeArgs[1] = String.class;
        typeArgs[2] = DisplayMetrics.class;
        typeArgs[3] = Integer.TYPE;
        Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod("parsePackage", typeArgs);
        valueArgs = new Object[4];
        valueArgs[0] = new File(apkPath);
        valueArgs[1] = apkPath;
        valueArgs[2] = metrics;
        valueArgs[3] = 0;
        Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser, valueArgs);
        Field appInfoFld = pkgParserPkg.getClass().getDeclaredField("applicationInfo");
        ApplicationInfo info = (ApplicationInfo) appInfoFld.get(pkgParserPkg);
        Class<?> assetMagCls = Class.forName(PATH_AssetManager);
        Constructor<?> assetMagCt = assetMagCls.getConstructor((Class[]) null);
        Object assetMag = assetMagCt.newInstance((Object[]) null);
        typeArgs = new Class[1];
        typeArgs[0] = String.class;
        Method assetMag_addAssetPathMtd = assetMagCls.getDeclaredMethod("addAssetPath", typeArgs);
        valueArgs = new Object[1];
        valueArgs[0] = apkPath;
        assetMag_addAssetPathMtd.invoke(assetMag, valueArgs);
        Resources res = context.getResources();
        typeArgs = new Class[3];
        typeArgs[0] = assetMag.getClass();
        typeArgs[1] = res.getDisplayMetrics().getClass();
        typeArgs[2] = res.getConfiguration().getClass();
        Constructor<?> resCt = Resources.class.getConstructor(typeArgs);
        valueArgs = new Object[3];
        valueArgs[0] = assetMag;
        valueArgs[1] = res.getDisplayMetrics();
        valueArgs[2] = res.getConfiguration();
        res = (Resources) resCt.newInstance(valueArgs);
        if (info.icon != 0) {
            Drawable icon = res.getDrawable(info.icon);
            return icon;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:android.content.pm.PackageParser.java

/**
 * Utility method that retrieves lightweight details about a single APK
 * file, including package name, split name, and install location.
 *
 * @param apkFile path to a single APK/*from  ww w .ja  va  2 s  .  com*/
 * @param flags optional parse flags, such as
 *            {@link #PARSE_COLLECT_CERTIFICATES}
 */
public static ApkLite parseApkLite(File apkFile, int flags) throws PackageParserException {
    final String apkPath = apkFile.getAbsolutePath();

    AssetManager assets = null;
    XmlResourceParser parser = null;
    try {
        assets = new AssetManager();
        assets.setConfiguration(0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                Build.VERSION.RESOURCES_SDK_INT);

        int cookie = assets.addAssetPath(apkPath);
        if (cookie == 0) {
            throw new PackageParserException(INSTALL_PARSE_FAILED_NOT_APK, "Failed to parse " + apkPath);
        }

        final DisplayMetrics metrics = new DisplayMetrics();
        metrics.setToDefaults();

        final Resources res = new Resources(assets, metrics, null);
        parser = assets.openXmlResourceParser(cookie, ANDROID_MANIFEST_FILENAME);

        final Signature[] signatures;
        if ((flags & PARSE_COLLECT_CERTIFICATES) != 0) {
            // TODO: factor signature related items out of Package object
            final Package tempPkg = new Package(null);
            collectCertificates(tempPkg, apkFile, 0);
            signatures = tempPkg.mSignatures;
        } else {
            signatures = null;
        }

        final AttributeSet attrs = parser;
        return parseApkLite(apkPath, res, parser, attrs, flags, signatures);

    } catch (XmlPullParserException | IOException | RuntimeException e) {
        throw new PackageParserException(INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION,
                "Failed to parse " + apkPath, e);
    } finally {
        IoUtils.closeQuietly(parser);
        IoUtils.closeQuietly(assets);
    }
}

From source file:org.appcelerator.titanium.view.TiDrawableReference.java

/**
 * Gets the bitmap, scaled to a width & height specified in TiDimension params.
 * @param destWidthDimension (null-ok) TiDimension specifying the desired width.  If .isUnitAuto()
 * then the width will be the source width.  If destWidthDimension is null, then the TiContext
 * will be used to determine the activity window's decor width and use that.
 * @param destHeightDimension (null-ok) TiDimension specifying the desired height.  If .isUnitAuto()
 * then the height will be the source height.  If destHeightDimension is null, then resulting height will
 * be at same ratio to the resulting width as the original height:width.
 * @return Bitmap, or null if any problem getting it.  Check logcat if null.
 *///from www .  j a va2s . c  om
public Bitmap getBitmap(View parent, TiDimension destWidthDimension, TiDimension destHeightDimension) {
    int srcWidth, srcHeight, destWidth, destHeight;

    Bounds bounds = peekBounds();
    srcWidth = bounds.width;
    srcHeight = bounds.height;

    if (srcWidth <= 0 || srcHeight <= 0) {
        Log.w(TAG, "Bitmap bounds could not be determined. If bitmap is loaded, it won't be scaled.");
        return getBitmap(); // fallback
    }

    if (parent == null) {
        Activity activity = softActivity.get();
        if (activity != null && activity.getWindow() != null) {
            parent = activity.getWindow().getDecorView();
        }
    }

    Bounds destBounds = calcDestSize(srcWidth, srcHeight, destWidthDimension, destHeightDimension, parent);
    destWidth = destBounds.width;
    destHeight = destBounds.height;

    // If src and dest width/height are same, no need to go through all the sampling and scaling jazz.
    if (srcWidth == destWidth && srcHeight == destHeight) {
        return getBitmap();
    }

    if (destWidth <= 0 || destHeight <= 0) {
        // calcDestSize() should actually prevent this from happening, but just in case...
        Log.w(TAG, "Bitmap final bounds could not be determined.  If bitmap is loaded, it won't be scaled.");
        return getBitmap();
    }

    InputStream is = getInputStream();
    if (is == null) {
        Log.w(TAG, "Could not open stream to get bitmap");
        return null;
    }

    Bitmap b = null;
    try {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inInputShareable = true;
        opts.inPurgeable = true;
        opts.inSampleSize = calcSampleSize(srcWidth, srcHeight, destWidth, destHeight);
        if (Log.isDebugModeEnabled()) {
            StringBuilder sb = new StringBuilder();
            sb.append("Bitmap calcSampleSize results: inSampleSize=");
            sb.append(opts.inSampleSize);
            sb.append("; srcWidth=");
            sb.append(srcWidth);
            sb.append("; srcHeight=");
            sb.append(srcHeight);
            sb.append("; finalWidth=");
            sb.append(opts.outWidth);
            sb.append("; finalHeight=");
            sb.append(opts.outHeight);
            Log.d(TAG, sb.toString());
        }

        Bitmap bTemp = null;
        try {
            oomOccurred = false;
            bTemp = BitmapFactory.decodeStream(is, null, opts);
            if (bTemp == null) {
                Log.w(TAG, "Decoded bitmap is null");
                return null;
            }

            if (Log.isDebugModeEnabled()) {
                StringBuilder sb = new StringBuilder();
                sb.append("decodeStream resulting bitmap: .getWidth()=" + bTemp.getWidth());
                sb.append("; .getHeight()=" + bTemp.getHeight());
                sb.append("; getDensity()=" + bTemp.getDensity());
                Log.d(TAG, sb.toString());
            }

            // Set the bitmap density to match the view density before scaling, so that scaling
            // algorithm takes destination density into account.
            DisplayMetrics displayMetrics = new DisplayMetrics();
            displayMetrics.setToDefaults();
            bTemp.setDensity(displayMetrics.densityDpi);

            // Orient the image when orientation is set.
            if (autoRotate) {
                // Only set the orientation if it is uninitialized
                if (orientation < 0) {
                    orientation = getOrientation();
                }
                if (orientation > 0) {
                    return getRotatedBitmap(bTemp, orientation);
                }
            }

            if (bTemp.getNinePatchChunk() != null) {
                // Don't scale nine-patches
                b = bTemp;
                bTemp = null;
            } else {
                Log.d(TAG, "Scaling bitmap to " + destWidth + "x" + destHeight, Log.DEBUG_MODE);

                // If anyDensity=false, meaning Android is automatically scaling
                // pixel dimensions, need to do that here as well, because Bitmap width/height
                // calculations do _not_ do that automatically.
                if (anyDensityFalse && displayMetrics.density != 1f) {
                    destWidth = (int) (destWidth * displayMetrics.density + 0.5f); // 0.5 is to force round up of dimension. Casting to int drops decimals.
                    destHeight = (int) (destHeight * displayMetrics.density + 0.5f);
                }

                // Created a scaled copy of the bitmap. Note we will get
                // back the same bitmap if no scaling is required.
                b = Bitmap.createScaledBitmap(bTemp, destWidth, destHeight, true);
            }

        } catch (OutOfMemoryError e) {
            oomOccurred = true;
            Log.e(TAG, "Unable to load bitmap. Not enough memory: " + e.getMessage(), e);

        } finally {
            // Recycle the temporary bitmap only if it isn't
            // the same instance as our scaled bitmap.
            if (bTemp != null && bTemp != b) {
                bTemp.recycle();
                bTemp = null;
            }
        }

    } finally {
        try {
            is.close();
        } catch (IOException e) {
            Log.e(TAG, "Problem closing stream: " + e.getMessage(), e);
        }
    }
    if (Log.isDebugModeEnabled()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Details of returned bitmap: .getWidth()=" + b.getWidth());
        sb.append("; getHeight()=" + b.getHeight());
        sb.append("; getDensity()=" + b.getDensity());
        Log.d(TAG, sb.toString());
    }
    return b;
}