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:
以下是我们的项目结构的外观: