Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

android - How can i get the apk file name and path programmatically?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
/**
 * 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;
}

EDIT In defense of catch (Throwable x) in this case. At first, now it is well-known that Checked Exceptions are Evil. At second, you cannot predict what may happen in future versions of Android. There already is a trend to wrap checked exceptions into runtime exceptions and re-throw them. (And a trend to do silly things that were unthinkable in the past.) As to the children of Error, well, if the package manager cannot find the apk that is running, it is the kind of problems for which Errors are thrown. Probably the last lines could be

    } catch (Throwable x) {
        return null;
    }

but I do not change working code without testing it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...