【Android APK】解析SD卡上的APK檔案

panpf發表於2019-04-15
public void parseApk(Context context, String apkFilePath){
    PackageManager packageManager = context.getPackageManager();
    PackageInfo packageInfo = packageManager.getPackageArchiveInfo(apkFilePath, 0);
    if(packageInfo != null){
        packageInfo.applicationInfo.sourceDir = apkFilePath;
        packageInfo.applicationInfo.publicSourceDir = apkFilePath;
        String name = packageInfo.applicationInfo.loadLabel(packageManager).toString();
        String packageName = packageInfo.packageName;
        String versionName = packageInfo.versionName;
        int versionCode = packageInfo.versionCode;
        Drawable iconDrawable = packageInfo.applicationInfo.loadIcon(packageManager);
    }
}
複製程式碼

需要注意的是在得到packageInfo後必須要設定applicationInfo的sourceDir和publicSourceDir,否則你在讀取label的時候會輸出如下錯誤資訊並丟擲異常 Failure retrieving text 0x7f050000 in package com.taskkiller.demo

你讀icon的時候會輸出如下錯誤資訊並丟擲異常 Failure retrieving icon 0x7f020005 in package com.sample.radio

這是因為label和icon都是在資源裡面的,不設定sourceDir和publicSourceDir就不能讀取資源裡面的資訊

相關文章