How Can I Get The Apk File Name And Path Programmatically?
Solution 1:
/**
* 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)
*/publicstatic String getApkName(Context context) {
StringpackageName= context.getPackageName();
PackageManagerpm= context.getPackageManager();
try {
ApplicationInfoai= pm.getApplicationInfo(packageName, 0);
Stringapk= ai.publicSourceDir;
return apk;
} catch (Throwable x) {
}
returnnull;
}
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) {
returnnull;
}
but I do not change working code without testing it.
Solution 2:
PackageManager.getPackageInfo() returns information about the package, and PackageInfo.applicationInfo field has required information about the application.
Solution 3:
Well, i would like to mark Yuri as the answer but i already knew about that stuff. So I went through each and every option from PackageManager.ApplicationInfo
and found .publicSourceDir
So a complete answer with code to my question would be
PackageManagerpm= getPackageManager();
try {
ApplicationInfoai= pInfo.getApplicationInfo(<packageName here>, 0);
StringsourceApk= ai.publicSourceDir;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So thanks again guys, got my brain goin once again Love StackOverflow!
Solution 4:
in above answer need change pInfo to pm
like this
PackageManagerpm= getPackageManager();
try {
ApplicationInfoai= pm.getApplicationInfo(<packageName here>, 0);
StringsourceApk= ai.publicSourceDir;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this answer by Seth
Post a Comment for "How Can I Get The Apk File Name And Path Programmatically?"