Android Retrofit下载文件进度

本教程介绍了如何在Android应用中使用Retrofit从URL下载文件并显示进度。通过添加@Streaming注解避免内存问题,并在AsyncTask中更新ProgressBar的进度。
摘要由CSDN通过智能技术生成

In this tutorial, we’ll create an android application which downloads a file from the URL using Retrofit.
To know the basics of Retrofit, visit this tutorial.

在本教程中,我们将创建一个Android应用程序,该应用程序使用Retrofit从URL下载文件。
要了解翻新的基础知识,请访问本教程

Android改造下载文件 (Android Retrofit Download File)

We can create a retrofit call in the following way in order to download file:

我们可以通过以下方式创建改造调用以下载文件:

@GET
Call<ResponseBody> downloadFileWithc(@Url String urlString);

We can pass the URL of the file we want to download. If we are downloading a file present in the resources we can do this:

我们可以传递要下载的文件的URL。 如果我们要下载资源中存在的文件,则可以执行以下操作:

@GET("/resource/path_to_file_with_extension")
Call<ResponseBody> downloadFileStatic();

It’s recommended to use a @Streaming annotation on top of the @GET for downloading files. Otherwise Retrofit would move the entire file into memory. Using @Streaming the bytes would be accessed currently without eating up the memory.

建议在@Streaming顶部使用@Streaming批注来下载文件。 否则,翻新会将整个文件移到内存中。 使用@Streaming可以在不占用内存的情况下当前访问字节。

When using @Streaming you must add the code that writes the downloaded data, into a separate thread.

使用@Streaming ,必须将写入下载数据的代码添加到单独的线程中。

Using the enqueue method we can start the request.
Inside it, we need to create an AsyncTask or use RxJava. We’ll go with the former in this tutorial.

使用enqueue方法,我们可以启动请求。
在其中,我们需要创建一个AsyncTask或使用RxJava。 在本教程中,我们将使用前者。

In the following android application that we are going to build, we’ll show the file download progress on a ProgressBar.

在下面将要构建的android应用程序中,我们将在ProgressBar上显示文件下载进度。

项目设置 (Project Setup)

Add the following dependencies to your app’s build.gradle:

将以下依赖项添加到应用程序的build.gradle中:

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.okhttp3:okhttps:3.10.0'

Add the following permissions in your Manifest:

在清单中添加以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

Following is how our Project Structure looks:

以下是我们的项目结构的外观:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值