Follow along.
In your module manifest, add
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
//Inside application block
<application>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_path"/>
</provider>
</application>
In your module res/xml folder, if not create this folder, with file provider_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
And use this method.
private fun updateApplication(activity: Activity) {
//This will get you the root directory path
val externalStoragePublicDirectory: String =
Environment.getExternalStorageDirectory().path
val externalStoragePublicDirectoryFile =
File(externalStoragePublicDirectory, "MyApp" + ".apk")
val uri = FileProvider.getUriForFile(
activity.applicationContext,
activity.applicationContext.packageName + ".provider",
externalStoragePublicDirectoryFile
)
val installAppIntent = Intent(Intent.ACTION_VIEW)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
.setDataAndType(
uri,
"application/vnd.android.package-archive"
)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true)
activity.startActivity(installAppIntent)
//This will close your app, remove if not needed
exitProcess(0)
}
Important, also go to your phone settings, search for unknown sources, enable it in old devices, but in new devices, search for your app and allow it the permission to install new app packages. Only then you will get the pop up to install the app.