我尝试使用 PackageInstaller 以编程方式安装 APK,但它没有任何错误就失败了。session.commit() 执行没有任何错误并调用回调 Intent。但是回调意图不会收到任何额外内容。
@Throws(IOException::class)
fun installPackage(context: Context, `in`: InputStream, packageName: String): Boolean {
Log.i("install","installer called")
Log.i("install","in iteration")
val packageInstaller: PackageInstaller = context.getPackageManager().getPackageInstaller()
val params = SessionParams(
SessionParams.MODE_FULL_INSTALL
)
params.setAppPackageName(packageName)
// set params
val sessionId = packageInstaller.createSession(params)
val session = packageInstaller.openSession(sessionId)
Log.i("id",""+sessionId)
addApkToInstallSession("india.apk",session);
val intent = Intent(context, InstallResultReceiver::class.java)
intent.setAction("PACKAGE_INSTALLED")
val pendingIntent = PendingIntent.getBroadcast(
context,
sessionId,
intent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
Log.i("t",""+packageInstaller.getSessionInfo(sessionId).toString())
try {
session.commit(pendingIntent.intentSender)
}catch(e:Exception){
Log.i("",""+e.stackTrace)
}
Log.i("Down","install committed")
return true
}
@Throws(IOException::class)
private fun addApkToInstallSession(assetName: String, session: PackageInstaller.Session) {
session.openWrite("package", 0, -1).use { packageInSession ->
assets.open(assetName).use { `is` ->
val buffer = ByteArray(16384)
var n: Int
while (`is`.read(buffer).also { n = it } >= 0) {
packageInSession.write(buffer, 0, n)
}
}
}
}