I need to automatically updat in my app. And I tried many things but I couldn’t make it. My solve is working in the emulator but not working in the real device.Emulator is Android 6.0 and real device is Android 8.1.
I try to automatically update my app.So, I’m dowloading my apk file from URL.I must open and install the downloaded file.That is working to android studio emulator.But not working in the real device.The downloaded file seems locked and cannot be opened from the file manager.And it doesn’t open in my application either and the application crashes. But it’s working to emulator.Relevant codes and images are below.
enter image description hereenter image description here
var destination =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.toString() + "/"
val fileName = "AXION.apk"
destination += fileName
val uri = Uri.parse("file://$destination")
val getUrl = "http://10.40.61.174/AxionAPK/AXION.apk"
val request = DownloadManager.Request(Uri.parse(getUrl))
val title = URLUtil.guessFileName(getUrl, null, null)
request.setTitle(title)
request.setMimeType("application/vnd.android.package-archive")
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,title)
//request.setDestinationInExternalPublicDir(this.filesDir.toString(),title)
//request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI)
val downloadManager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
downloadManager.enqueue(request)
val finalDestination = destination
val onComplete: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(ctxt: Context, intent: Intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val contentUri = FileProvider.getUriForFile(
ctxt,
BuildConfig.APPLICATION_ID + ".provider",
File(finalDestination)
)
val openFileIntent = Intent(Intent.ACTION_VIEW)
openFileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
openFileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
openFileIntent.data = contentUri
startActivity(openFileIntent)
unregisterReceiver(this)
finish()
Toast.makeText(this@LogonActivity,"Kuruluyor 1 ...",Toast.LENGTH_LONG).show()
} else {
val install = Intent(Intent.ACTION_VIEW)
install.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
/*
install.setDataAndType(
uri,
"application/vnd.android.package-archive"
)
*/
val f = File(destination)
install.setDataAndType(Uri.fromFile(f),"application/vnd.android.package-archive");
startActivity(install)
unregisterReceiver(this)
finish()
Toast.makeText(this@LogonActivity,"Kuruluyor 2 ...",Toast.LENGTH_LONG).show()
}
}
}
registerReceiver(onComplete, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
Halil Akyıldız is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.