Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 PackageManager 讀取已安裝與未安裝 APK 的資訊

編輯:關於 Android 程式設計

做應用市場、插件化或動態加載時,經常需要讀取 APK 的資訊。Android 中承擔這項工作的核心類是 PackageManager,它既能查詢系統中已安裝的應用,也能解析一個尚未安裝的 APK 檔案。

一、讀取已安裝應用的名稱與圖示

PackageManager pm = getPackageManager();
List<PackageInfo> apkInfos = pm.getInstalledPackages(0);
ArrayList<String> infos_name = new ArrayList<String>();   // 存放 label
ArrayList<Drawable> infos_icon = new ArrayList<Drawable>(); // 存放啟動圖示

for (int i = 0; i < apkInfos.size(); i++) {
    PackageInfo apk = apkInfos.get(i);
    String name = (String) pm.getApplicationLabel(apk.applicationInfo);
    Drawable icon = pm.getApplicationIcon(apk.applicationInfo);
    infos_icon.add(icon);
    infos_name.add(name);
}

二、讀取指定應用的 Activity、Service 與 Receiver

只要給 getPackageInfo 傳入合適的 flag,就能把元件資訊一併帶回來。

List<PackageInfo> packagesInfo = pm.getInstalledPackages(0);
for (PackageInfo packageInfo : packagesInfo) {
    Log.d("TAG", "packageInfo NAME IS :" + packageInfo.packageName);
}

try {
    // 一次帶回權限、服務與廣播接收器
    PackageInfo packageInfo = pm.getPackageInfo("com.example.pertest",
            PackageManager.GET_PERMISSIONS
                    | PackageManager.GET_SERVICES
                    | PackageManager.GET_RECEIVERS);

    ActivityInfo[] activities = packageInfo.activities;
    if (activities != null) {
        for (ActivityInfo activityInfo : activities) {
            Log.d("TAG", "the activity " + activityInfo.toString()
                    + "==" + packageInfo.versionCode
                    + "===" + packageInfo.versionName);
        }
    } else {
        Log.d("TAG", "the activity is null");
    }

    ServiceInfo[] serviceInfos = packageInfo.services;
    for (ServiceInfo serviceInfo : serviceInfos) {
        Log.d("TAG", "service name is :" + serviceInfo.name);
    }

    for (ActivityInfo receiver : packageInfo.receivers) {
        Log.d("TAG", "receiver is :" + receiver.name);
    }
} catch (NameNotFoundException e) {
    e.printStackTrace();
}

三、讀取未安裝 APK 的圖示與名稱

對於一顆躺在檔案系統裡的 APK,可以先用 getPackageArchiveInfo 解析出 PackageInfo,再把 sourceDir 指向該檔案,最後交由 PackageManager 取用資源。這在動態加載外掛 APK 時非常實用。

public static Drawable getAppIcon(Context context, String apkFilepath) {
    PackageManager pm = context.getPackageManager();
    PackageInfo pkgInfo = getPackageInfo(context, apkFilepath);
    if (pkgInfo == null) {
        return null;
    }
    ApplicationInfo appInfo = pkgInfo.applicationInfo;
    if (Build.VERSION.SDK_INT >= 8) {
        appInfo.sourceDir = apkFilepath;
        appInfo.publicSourceDir = apkFilepath;
    }
    return pm.getApplicationIcon(appInfo);
}

public static CharSequence getAppLabel(Context context, String apkFilepath) {
    PackageManager pm = context.getPackageManager();
    PackageInfo pkgInfo = getPackageInfo(context, apkFilepath);
    if (pkgInfo == null) {
        return null;
    }
    ApplicationInfo appInfo = pkgInfo.applicationInfo;
    if (Build.VERSION.SDK_INT >= 8) {
        appInfo.sourceDir = apkFilepath;
        appInfo.publicSourceDir = apkFilepath;
    }
    return pm.getApplicationLabel(appInfo);
}

// 解析未安裝 APK,取得其中的 Activity 與 Service 資訊
public static PackageInfo getPackageInfo(Context context, String apkFilepath) {
    PackageManager pm = context.getPackageManager();
    PackageInfo pkgInfo = null;
    try {
        pkgInfo = pm.getPackageArchiveInfo(apkFilepath,
                PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return pkgInfo;
}

四、動態加載:建立 DexClassLoader

拿到 DEX 的類加載器,才能反射調用外掛 APK 裡的類。

String mNativeLibDir = mContext.getDir("pluginlib", Context.MODE_PRIVATE).getAbsolutePath();

private DexClassLoader createDexClassLoader(String dexPath) {
    File dexOutputDir = mContext.getDir("dex", Context.MODE_PRIVATE);
    String dexOutputPath = dexOutputDir.getAbsolutePath();
    return new DexClassLoader(dexPath, dexOutputPath, mNativeLibDir, mContext.getClassLoader());
}

四個參數的含義:

1. dexPath:APK 檔案的存放路徑。

2. dexOutputPath:該 APK 對應 dex 檔案的輸出目錄,不可為 null。

3. libraryPath:目標類中使用的 C/C++ 庫路徑列表,多個目錄以 File.pathSeparator 分隔,可為 null。

4. parent:父類加載器,一般傳入當前執行類的類加載器。

五、加載未安裝 APK 的資源

外掛 APK 使用不同的 Context,因此需要自己拼出一套 AssetManager 與 Resources。

private AssetManager createAssetManager(String dexPath) {
    try {
        AssetManager assetManager = AssetManager.class.newInstance();
        Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
        addAssetPath.invoke(assetManager, dexPath);
        return assetManager;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

private Resources createResources(AssetManager assetManager) {
    Resources superRes = mContext.getResources();
    return new Resources(assetManager, superRes.getDisplayMetrics(), superRes.getConfiguration());
}

這樣得到的 assetManager 與 resources,後續就能像平時一樣正常使用了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved