在 Android 中使用 kotlin 下载文件并将其保存到下载文件夹

Downloading file and saving it to download folder using kotlin in Android

我正在尝试从网络服务器下载一个 apk 文件并将其存储在下载文件夹中。我正在使用燃料库

Fuel.download("https://mypath/app.apk").destination { 
    response, url -> val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()) File(dir, "abcd.apk")    
}.progress {
    readBytes, totalBytes -> val progress = readBytes.toFloat() / totalBytes.toFloat()
    Log.d("log",progress.toString())
}.response {
    req, res, result -> Log.d("log","download completed ")    
    Log.d("log",Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/abcd.apk")
}

我在 response 中收到 bytesArray,但文件没有保存到下载文件夹。我的 Manifest 文件中有 write_external_storage。请让我知道我错过了什么?

正如您在评论中提到的,您将 targetSdkVersion 用作 23。从 Android 6.0(API 级别 23)开始,如果您将 targetSdkVersion 设置为 23在您的应用中,您必须在您的应用中实施 rumtime 权限。

要实现它请参考这里的官方文档Requesting Permissions at Run Time

fun storeImage(link: String) : String {
    val policy: StrictMode.ThreadPolicy = StrictMode.ThreadPolicy.Builder().permitAll().build()
    StrictMode.setThreadPolicy(policy)
    val cw = ContextWrapper(applicationContext)
    val directory: File = cw.getDir("imageDir", Context.MODE_PRIVATE)
    val pictureFile = File(directory, "backgroundImage.gif")
    URL(link).openStream().use { input ->
        FileOutputStream(pictureFile).use { output ->
            input.copyTo(output)
            Log.e("DD GIF", "storeImage: FILE SAVED" )
            return "SAVED"
        }
    }
}

它对我有用。