Andoid:靜默安裝apk

2020-09-28 09:10:23

以下方法可以可以實現靜默安裝apk, 不過沒辦法具體判斷apk是否安裝成功
不過可以註冊App監聽的廣播,
詳情可以看我的這一篇文章:Android:監聽裝置應用改變

public static boolean installApp(String apkFilePath) {
        LogUtil.Logd("installApk  apkFilePath:" + apkFilePath);
        File file = new File(apkFilePath);
        if (!file.exists() || !file.isFile()) {
            LogUtil.Logd("安裝apk 檔案錯誤");
            return false;
        }
        PackageManager packageManager = CommonLib.getContext().getPackageManager();
        boolean success = false;
        try {
            Class<?> clazz = CommonLib.getContext().getClassLoader().loadClass("android.app.PackageInstallObserver");
            Method method = packageManager.getClass().getDeclaredMethod("installPackage",
                    Uri.class, clazz, int.class, String.class);
            method.setAccessible(true);
            //|0x00000040|0x00001000
            method.invoke(packageManager, Uri.fromFile(file), clazz.newInstance(), 0x00000002, "你的包名");
            success = true;
        } catch (Exception e) {
            LogUtil.Logd("method.invoke  安裝失敗!");
            e.printStackTrace();
        } finally {
            if (!success) {
                LogUtil.Logd("HandlerConstanst.mApkInstallFailed");
                return false;
            } else {
                LogUtil.Logd("installApk ApkUpdateEnum.INSTALLING");
                return true;
            }
        }
    }

覺得有用的話別忘了點個贊吶φ(>ω<*)