简体   繁体   中英

Android package installer failed silently

I tried to install the APK programmatically using PackageInstaller but it is failing without any error. The session.commit() executing without any error and calls the callback Intent. But callback intent doesn't receive any extras.

 @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)
                }
            }
        }
    }

You have to change the flags on PendingIntent.getBroadcast(). Try the following:

var flags = 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    flags = PendingIntent.FLAG_MUTABLE
}
val pendingIntent = PendingIntent.getBroadcast(
    context,
    sessionId,
    intent,
    flags
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM