PackageInstaller fails with INSTALL_FAILED_INVALID_APK

Published

I would like my application to download an APK file of another app, and then install it (not silently).
I tried doing this using the PackageInstaller. I wrote this function:

val packageInstaller = MainApplication.context.packageManager.packageInstaller

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

val sessionId = packageInstaller.createSession(params)
val session = packageInstaller.openSession(sessionId)

val out = session.openWrite(MainApplication.context.packageName, 0, -1)
val fis = file.inputStream()
fis.copyTo(out)
session.fsync(out)
out.close()

val intent = Intent(MainApplication.context, InstallReceiver::class.java)
val pi = PendingIntent.getBroadcast(
    MainApplication.context,
    3439,
    intent,
    PendingIntent.FLAG_UPDATE_CURRENT
)

session.commit(pi.intentSender)
session.close()

InstallReceiver

package com.example.myapp

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.media.AudioManager
import android.media.ToneGenerator
import android.util.Log

private const val TAG = "AppInstaller"

class InstallReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {

        when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -1)) {
            PackageInstaller.STATUS_PENDING_USER_ACTION -> {
                val activityIntent =
                    intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)

                context.startActivity(activityIntent?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
            }
            PackageInstaller.STATUS_SUCCESS ->
                ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100)
                    .startTone(ToneGenerator.TONE_PROP_ACK)
            else -> {
                val msg = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)

                Log.e(TAG, "received $status and $msg")
            }
        }
    }
}

And this is the error I get:

E/AppInstaller: received 4 and INSTALL_FAILED_INVALID_APK: /data/app/vmdl1985945050.tmp/com.example.myapp specified package com.example.myapp inconsistent with com.example.otherapp

I’ve already verified that the downloaded APK file is not corrupted, and can be installed by just opening it with any file manager.

Source: Android Questions

Published
Categorized as android, kotlin

Answers

Leave a Reply

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq