| | |
| | | |
| | | suspend fun downloadCommonFileToExternalFilesDir(context: Context, url: String, filename: String, install: Boolean) { |
| | | val tmpFile = File(context.getExternalFilesDir(null), filename) |
| | | try{ |
| | | try { |
| | | if (tmpFile.exists()) { |
| | | return |
| | | } |
| | |
| | | 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) // 下载成功时返回文件 |
| | |
| | | }) |
| | | } |
| | | |
| | | // 等待下载完成 |
| | | |
| | | 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) |