由于某些原因,我的应用可以使用不同的apk名称进行安装。在启动时,我想知道apk文件的名称。你知道如何做吗?
谢谢!
final PackageManager pm = getPackageManager();
String apkName = "example.apk";
String fullPath = Environment.getExternalStorageDirectory() + "/" + apkName;
PackageInfo info = pm.getPackageArchiveInfo(fullPath, 0);
您可以使用以下方法获取它:
info.versionCod
并且
info.versionName
public static String getAppLabel(PackageManager pm, String pathToApk) {
PackageInfo packageInfo = pm.getPackageArchiveInfo(pathToApk, 0);
if (Build.VERSION.SDK_INT >= 8) {
// those two lines do the magic:
packageInfo.applicationInfo.sourceDir = pathToApk;
packageInfo.applicationInfo.publicSourceDir = pathToApk;
}
CharSequence label = pm.getApplicationLabel(packageInfo.applicationInfo);
return label != null ? label.toString() : null;
}
试试这个:
ActivityManager actMngr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
string runningPkg = actMngr.getRunningTasks(1).get(0).topActivity.getPackageName();
PackageManager pm = context.getPackageManager();
ApplicationInfo ai = pm.getApplicationInfo(runningPkg , 0);
添加:
如果您无法获取apk名称,则可以将其与已安装的pkg进行比较,然后获取相应的应用程序名称。您可以像这样获取已安装应用程序的pkg名称和应用程序名称:
ArrayList<PackageInfo> res = new ArrayList<PackageInfo>();
PackageManager pm = ctx.getPackageManager();
List<PackageInfo> packs = pm.getInstalledPackages(0);
for(int i=0;i<packs.size();i++) {
PackageInfo p = packs.get(i);
String description = (String) p.applicationInfo.loadDescription(pm);
String label= p.applicationInfo.loadLabel(pm).toString();
//Continue to extract other info about the app...
}
<uses-permission android:name="android.permission.GET_TASKS" />
这可以通过从已经打包好的apk文件中使用getPackageArchiveInfo来实现:
PackageInfo package_info = pm.getPackageArchiveInfo(file_path_to_apk, 0);
你可以试试这个,对我很有效:
String versionName = "null"; //String apk versionName
int versionCode = -1; //int versionCode
String APKFilePath = "/storage/emulated/0/apkname.apk"; //For example
PackageManager pm = getPackageManager();
PackageInfo packageInfo = pm.getPackageArchiveInfo(APKFilePath, 0);
// the secret are these two lines
packageInfo.applicationInfo.sourceDir = APKFilePath;
packageInfo.applicationInfo.publicSourceDir = APKFilePath;
Drawable APKicon = packageInfo.applicationInfo.loadIcon(pm); //drawable apk icon
String AppName = (String)packageInfo.applicationInfo.loadLabel(pm); // String apk name
versionName = packageInfo.versionName; //String version name
versionCode = packageInfo.versionCode; //int version code
apk_icon.setImageDrawable(APKicon); //ImageView apk icon
Apkpackage.setText(packageInfo.packageName); //TextView apk package name
Apkname.setText(AppName); //TextView apk name
Apkversion.setText(String.format("Version Name: %s Version Code:%d", versionName, versionCode)); //TextView versionName and versionCode