7

I want to get the exact file name of a program if I already know the package name of the target apk. For instance, if I know the package name of my apk, which is com.packagename, how can I get the exact path and file name of that package? Btw, i don't want to get just MY apk location, i want the location of any package name i apply. SystemTuner pro is able to do this so i know it is possible, just not sure how.

Thanks guys!

4

4 回答 4

7
/**
 * Get the apk path of this application.
 * @param context any context (e.g. an Activity or a Service)
 * @return full apk file path, or null if an exception happened (it should not happen)
 */
public static String getApkName(Context context) {
    String packageName = context.getPackageName();
    PackageManager pm = context.getPackageManager();
    try {
        ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
        String apk = ai.publicSourceDir;
        return apk;
    } catch (Throwable x) {
    }
    return null;
}

编辑catch (Throwable x)为在这种情况下 辩护。起初,现在众所周知Checked Exceptions 是 Evil。其次,您无法预测未来版本的 Android 会发生什么。已经有将检查的异常包装到运行时异常中并重新抛出它们的趋势。(并且有一种趋势是做一些过去无法想象的愚蠢事情。)对于 Error 的孩子,如果包管理器找不到正在运行的 apk,那就是引发 Errors 的那种问题。可能最后几行可能是

    } catch (Throwable x) {
        return null;
    }

但我不会在不测试的情况下更改工作代码。

于 2015-07-21T09:48:44.607 回答
4

PackageManager.getPackageInfo()返回有关包的信息,PackageInfo.applicationInfo字段包含有关应用程序的必需信息。

于 2013-06-06T22:30:51.103 回答
3

好吧,我想将 Yuri 标记为答案,但我已经知道那件事了。所以我浏览了每一个选项PackageManager.ApplicationInfo并发现.publicSourceDir

因此,对我的问题的代码的完整答案将是

PackageManager pm = getPackageManager();
    try {
        ApplicationInfo ai = pInfo.getApplicationInfo(<packageName here>, 0);
        String sourceApk = ai.publicSourceDir;
    } catch (NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

所以再次感谢伙计们,让我的大脑再次开始爱 StackOverflow!

于 2013-06-06T22:45:28.580 回答
1

在上面的答案中需要将 pInfo 更改为 pm

像这样

PackageManager pm = getPackageManager();
try {
    ApplicationInfo ai = pm.getApplicationInfo(<packageName here>, 0);
    String sourceApk = ai.publicSourceDir;
} catch (NameNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

赛斯的这个回答

于 2019-05-19T20:20:12.443 回答