Android - 使用 PackageInstaller 和 PackageInstaller.Session 静默安装 APK [英] Android - Install APK silently with PackageInstaller and PackageInstaller.Session

查看:287
本文介绍了Android - 使用 PackageInstaller 和 PackageInstaller.Session 静默安装 APK的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看 Android (AOSP) 的源代码,installPackage 被标记为已弃用,并检查 Android 的 PackageManager 应用程序,它使用 PackageInstaller 类创建一个 PackageInstaller.Session 实例来执行 APK 的安装.

Looking into the sources of Android (AOSP), the installPackage is labled deprecated and inspecting the PackageManager application of Android, it uses the PackageInstaller class to create a PackageInstaller.Session instance to perform the installation of an APK.

我正在尝试在我的应用程序中做同样的事情.我使用系统密钥签名,并且在清单中包含了 INSTALL_PACKAGES 权限.

I am trying to do the same in my application. I am signed with the system key and I did include the INSTALL_PACKAGES permission in the manifest.

这是我的代码:

    val packageName = "com.spotify.music"
    val inputStream = File(filesDir, "spotify.apk").inputStream()

    // ...

    val packageInstaller = context.packageManager.packageInstaller
    val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL)
    params.setAppPackageName(packageName)

    val sessionId = packageInstaller.createSession(params)
    val session = packageInstaller.openSession(sessionId)
    val out = session.openWrite("COSU", 0, -1)
    inputStream.copyTo(out)
    session.fsync(out)
    inputStream.close()
    out.close()
    session.commit(null)

但是,我收到以下奇怪的空指针异常:

However, I am getting the following weird null pointer exception:

安装时出错:java.lang.NullPointerException:尝试在空对象引用上调用虚方法void android.app.AppOpsManager.checkPackage(int, java.lang.String)"

有人知道这里出了什么问题吗?

Does anybody have a clue what's going wrong here?

推荐答案

您不能将 null 传递给 session.commit().请参阅 Android 开发人员 上的文档.您需要的是一个 IntentSender,它是从 PendingIntent 中获取的,而 PendingIntent 又应包含您的应用可以接收的 Intent(可以在 Activity、Service 或 BroadcastReceiver 中).

You can't pass null to session.commit(). See the doc at Android Developers. What you need is an IntentSender, which you get from a PendingIntent which in turn should contain an intent that your app can receive (can be in either of an Activity, a Service or a BroadcastReceiver).

提交会话后,结果将作为附加内容包含在收到的意图中.

When the session is committed the result will be included as extras in the received intent.

这篇关于Android - 使用 PackageInstaller 和 PackageInstaller.Session 静默安装 APK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆