This commit is contained in:
parent
850550c392
commit
75909d953c
|
|
@ -34,22 +34,16 @@ class UpdateManager(private val context: Context) {
|
|||
private val fileName = "StandApp_Update.apk"
|
||||
|
||||
/**
|
||||
* 获取或创建公共下载目录下的文件 URI
|
||||
* 获取应用缓存目录下的临时文件 URI,避免申请外部存储权限
|
||||
*/
|
||||
private fun getPublicDownloadUri(): Uri? {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val contentValues = ContentValues().apply {
|
||||
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
|
||||
put(MediaStore.MediaColumns.MIME_TYPE, "application/vnd.android.package-archive")
|
||||
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
|
||||
private fun getCacheFileUri(): Uri {
|
||||
val cacheDir = context.externalCacheDir ?: context.cacheDir
|
||||
val file = File(cacheDir, fileName)
|
||||
if (file.exists()) {
|
||||
file.delete()
|
||||
}
|
||||
val contentResolver = context.contentResolver
|
||||
return contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues)
|
||||
} else {
|
||||
val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName)
|
||||
return Uri.fromFile(file)
|
||||
}
|
||||
}
|
||||
|
||||
fun checkUpdate() {
|
||||
val serverUrl = AppConfig.getServerUrl(context)
|
||||
|
|
@ -216,10 +210,9 @@ class UpdateManager(private val context: Context) {
|
|||
var targetUri: Uri? = null
|
||||
|
||||
try {
|
||||
targetUri = getPublicDownloadUri()
|
||||
if (targetUri == null) throw IOException("无法创建文件记录")
|
||||
|
||||
outputStream = context.contentResolver.openOutputStream(targetUri)
|
||||
targetUri = getCacheFileUri()
|
||||
val file = File(targetUri.path!!)
|
||||
outputStream = FileOutputStream(file)
|
||||
inputStream = body.byteStream()
|
||||
|
||||
val totalBytes = body.contentLength()
|
||||
|
|
@ -228,7 +221,7 @@ class UpdateManager(private val context: Context) {
|
|||
var totalRead: Long = 0
|
||||
|
||||
while (inputStream.read(buffer).also { bytesRead = it } != -1) {
|
||||
outputStream?.write(buffer, 0, bytesRead)
|
||||
outputStream.write(buffer, 0, bytesRead)
|
||||
totalRead += bytesRead
|
||||
|
||||
if (totalBytes > 0) {
|
||||
|
|
@ -239,11 +232,11 @@ class UpdateManager(private val context: Context) {
|
|||
}
|
||||
}
|
||||
}
|
||||
outputStream?.flush()
|
||||
outputStream.flush()
|
||||
|
||||
handler.post {
|
||||
progressDialog?.dismiss()
|
||||
Toast.makeText(context.applicationContext, "下载完成,文件已保存到系统下载目录", Toast.LENGTH_SHORT).show()
|
||||
Toast.makeText(context.applicationContext, "下载完成,正在安装...", Toast.LENGTH_SHORT).show()
|
||||
installApk(targetUri)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
|
|
|
|||
Loading…
Reference in New Issue