wangrong
2024-11-30 bd54352f44f33caef57a8dbb541e5e84a372dcbb
app/src/main/java/com/shsening/autouploadvideos/utils/Utils.kt
@@ -278,7 +278,7 @@
    suspend fun downloadCommonFileToExternalFilesDir(context: Context, url: String, filename: String, install: Boolean) {
        val tmpFile = File(context.getExternalFilesDir(null), filename)
        try{
        try {
            if (tmpFile.exists()) {
                return
            }
@@ -292,17 +292,20 @@
                    override fun onFailure(call: Call, e: IOException) {
                        deferred.completeExceptionally(e) // 下载失败时标记为异常
                    }
                    override fun onResponse(call: Call, response: Response) {
                        response.use {
                            if (!response.isSuccessful) {
                                deferred.completeExceptionally(IOException("Unexpected code $response")) // 如果响应不成功,标记为异常
                                return
                            }
                            tmpFile.outputStream().use { outputStream ->
                                outputStream.write(response.body?.bytes())
                            }
                            if (install) {
                                installApk(context,tmpFile)
                                installApk(context, tmpFile)
                            }
                            deferred.complete(Unit) // 下载成功时返回文件
@@ -311,19 +314,22 @@
                })
            }
            // 等待下载完成
            Toast.makeText(context, filename + " " + AppConfig.MSG_DOWNLOAD_FINISHED, Toast.LENGTH_SHORT).show()
            // Switch to main thread for Toast
            withContext(Dispatchers.Main) {
                Toast.makeText(context, "$filename ${AppConfig.MSG_DOWNLOAD_FINISHED}", Toast.LENGTH_SHORT).show()
            }
            deferred.await()
        }catch(e:Exception){
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(context, filename+" download fails, Please try again later!", Toast.LENGTH_SHORT)
                    .show()
            // Switch to main thread for Toast
            withContext(Dispatchers.Main) {
                Toast.makeText(context, "$filename download fails, Please try again later!", Toast.LENGTH_SHORT).show()
            }
        }
    }
    fun installApk(context: Context,apkFile: File) {
        val intent = Intent(Intent.ACTION_VIEW)
        val apkUri = FileProvider.getUriForFile(context, AppConfig.FILE_PROVIDER, apkFile)