从sdcard文件中获取apk信息

时间:2012-06-07 09:07:15

标签: android apk

        String apkPath = apk.getAbsolutePath();
        Log.i(getClass().getName(), "addApk(): apkPath = " + apkPath);
        PackageInfo localPackageInfo = pm.getPackageArchiveInfo(apkPath, 0);
        localPackageInfo.applicationInfo.sourceDir = apkPath;//! null point exception

无法获取apk的图标,名称,版本等。我也尝试了幻数8192而不是0,但也无法正常工作。 有人有什么建议吗? Thx提前!


我将代码更改为:

        PackageInfo pi = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        if (pi != null) {
            ApplicationInfo ai = pi.applicationInfo;
            Drawable appIcon = pm.getApplicationIcon(ai);
            String appName = pm.getApplicationLabel(ai).toString();
            String appVersion = pi.versionName;
            String pkgName = ai.packageName;

            Log.i(getClass().getName(), "pkgName = " + pkgName + ", appName = " + appName + ", appVersion = " + appVersion);
            adapter.add(new InstallItem(pkgName, appIcon, appName, appVersion));
        }

得到这样的输出:

pkgName = com.chaozh.iReaderFree,appName = com.chaozh.iReaderFree,appVersion = 1.3.2.0 ......

如您所见,我无法获取应用名称,其图标始终是默认的相同图标。 我在市场上厌倦了其他安装人员并且工作得很好,所以任何人都告诉我该怎么办? THX。

3 个答案:

答案 0 :(得分:4)

您可以使用PackageManager方法getPackageArchiveInfo从APK文件中检索信息。假设您的APK位于SD卡的根目录中,您可以使用以下代码:

    String apkPath = Environment.getExternalStorageDirectory().getAbsolutePath() 
                   + "/MyApp.apk";
    PackageManager pm = getPackageManager();

    PackageInfo info = pm.getPackageArchiveInfo(apkPath, 
                           PackageManager.GET_ACTIVITIES);
    //Log.i("ActivityInfo", "Package name is " + info.packageName);

    for (android.content.pm.ActivityInfo a : info.activities) {
        Log.i("ActivityInfo", a.name);
    }

您可以在ActivityInfo和PackageInfo对象中找到大量其他信息。

答案 1 :(得分:2)

这是正确答案,有一些技巧(SDK> 8!):

public Drawable getApkIcon(String path){      
    PackageManager pm = getPackageManager();      
    PackageInfo info = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);      
    if(info != null){      
        ApplicationInfo appInfo = info.applicationInfo;

        if(Build.VERSION.SDK_INT >= 8){
            appInfo.sourceDir = path;
            appInfo.publicSourceDir = path;
        }

        return appInfo.loadIcon(pm);
    }           
    return null;
}

答案 2 :(得分:0)

最简单的方法 只需使用packageName

获取任何应用的图标即可
public static final Drawable getIconOfAppUsingPackageName(Context context,String packageName)
{
 Drawable icon = context.getPackageManager().getApplicationIcon(packageName);
 imageView.setImageDrawable(icon);
 return icon;
}