如何在Android编程中下载和安装apk文件。我需要从包含apk file...The的URL下载和安装新的更新,通常的步骤是检查是否有新版本,然后下载并安装它。
这是我现在使用的代码:
val extStorageDirectory = Environment.getExternalStorageDirectory().toString()
val folder = File(extStorageDirectory)
Log.e("extStorageDirectory", extStorageDirectory)
folder.mkdir()
val file = File(folder, "AppName." + "apk")
try {
file.createNewFile()
/**
* APKURL is your apk file url(server url)
*/
DownloadFile(apkLink, file)
} catch (e1: IOException) {
// e1.printStackTrace()
Log.e("e1", e1.toString())
}
private fun DownloadFile(fileURL: String, directory: File) {
try {
val f = FileOutputStream(directory)
val u = URL(fileURL)
val c = u.openConnection() as HttpURLConnection
c.requestMethod = "GET"
//c.setDoOutput(true);
c.connect()
val `in` = c.inputStream
val buffer = ByteArray(1024)
var len1 = 0
while (`in`.read(buffer).also { len1 = it } > 0) {
f.write(buffer, 0, len1)
}
f.close()
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(
Uri.fromFile(
File(
Environment.getExternalStorageDirectory()
.toString() + "AppName.apk"
)
), "application/vnd.android.package-archive"
)
startActivity(intent)
} catch (e: Exception) {
println("exception in DownloadFile: --------$e")
e.printStackTrace()
Log.e("exception in DownloadFile", e.toString())
}
}我得到了这个错误: java.io.IOException:不允许的操作
发布于 2022-07-01 06:48:06
在您的设备中设置->安全->未知源->允许安装来自未知源的应用程序。因为您不使用CHplay,所以必须接受其他来源的apk。
https://stackoverflow.com/questions/72473222
复制相似问题