0

I'm working on an installer application with system permissions in which I need to resolve the package name of an APK that is not yet installed.

Just to be clear, I'm talking about doing this within an android app -- I already know how to do this on a desktop.

I've already tried treating the APK as a ZipFile and pulling it from the AndroidManifest.xml, but this doesn't work because the text is encrypted.

Are there any other ways to do this within the Android framework?

Thanks for any help.

TomB
  • 21
  • 2
  • This problem was resolved here in this link. http://stackoverflow.com/questions/4470139/how-to-get-application-or-package-info-from-the-apk-file-in-the-android-applicat – Luciano Moura Feb 20 '15 at 19:22
  • 1
    Like I said, I tried that. It didn't work because the text in AndroidManifest.xml was garbled. Unless there's a way to make it readable, I can't do it that way. – TomB Feb 20 '15 at 19:57

1 Answers1

2

I've found a solution. I went into the AOSP source and found some hidden methods in AssetManager that do the trick when invoked via reflection. System permissions aren't needed.

    public static String extractPackageName(Context ctx, String apkPath) {
    try {
        AssetManager assmgr = ctx.getAssets();

        Method addAssetPathMethod = assmgr.getClass().getMethod("addAssetPath", String.class);
        Method setConfigurationMethod = assmgr.getClass().getMethod("setConfiguration",
                int.class, int.class, String.class, int.class, int.class,
                int.class,int.class, int.class, int.class, int.class, int.class,
                int.class, int.class, int.class, int.class, int.class, int.class);

        int cookie = ((Integer) addAssetPathMethod.invoke(assmgr, apkPath)).intValue();

        if (cookie != 0) {
            final DisplayMetrics metrics = new DisplayMetrics();
            metrics.setToDefaults();
            setConfigurationMethod.invoke(assmgr, 0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Build.VERSION.SDK_INT);
            XmlResourceParser parser = assmgr.openXmlResourceParser(cookie, "AndroidManifest.xml"); 
            int type;
            while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) {}
            String packageName = parser.getAttributeValue(null, "package");
            return packageName;
        }

    } catch (Exception e) {
    }

    return null;
}
TomB
  • 21
  • 2
  • "I went into the AOSP source". Post the link to this file from online git repo. Where did you pull this from exactly? – Jared Burrows Feb 20 '15 at 21:39
  • @JaredBurrows - this is not an extract from AOSP, rather it is an invocation via reflection of code already present on the device. Searching through AOSP is merely how the author figured out what to do. – Chris Stratton Feb 20 '15 at 21:42