Android: how to get the name of apk file programmatically?

后端 未结 4 1272
失恋的感觉
失恋的感觉 2020-12-10 16:37

For some reasons, my app can be installed with different apk names. At launch, I would like to know what is the name of the apk file. Do you know how to do that ?

Th

相关标签:
4条回答
  • 2020-12-10 17:05

    This is achieved with getPackageArchiveInfo from an already packaged apk file:

      PackageInfo package_info = pm.getPackageArchiveInfo(file_path_to_apk, 0);
    
    0 讨论(0)
  • 2020-12-10 17:06

    The apk or app name can be retrieved using package manager. According to alex's answer here - https://stackoverflow.com/a/30348666/2026280

    Assuming you have the path of the apk file.

    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;
    }
    
    0 讨论(0)
  • 2020-12-10 17:17
    final PackageManager pm = getPackageManager();
    String apkName = "example.apk";
    String fullPath = Environment.getExternalStorageDirectory() + "/" + apkName;        
    PackageInfo info = pm.getPackageArchiveInfo(fullPath, 0);
    

    you can got it with:

    info.versionCod
    

    and

    info.versionName
    

    hope this help you

    0 讨论(0)
  • 2020-12-10 17:21

    try this:

    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);
    

    Added:

    If you are not getting the apk name then you can compare it with intalled pkg and get the corresponding app name. You can fetch the installed app's pkg name and app name like this:

    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...
    }
    

    Note: Add this permission to the manifest file:

    <uses-permission android:name="android.permission.GET_TASKS" />
    
    0 讨论(0)
提交回复
热议问题