android改造下载进度

时间:2017-02-08 16:46:02

标签: android

我是新来的改造。我搜索过但没有找到简单的答案。我想知道如何在通知栏中显示下载进度或至少显示进度对话框,该对话框指定进程的百分比和下载文件的大小。 这是我的代码:

public interface ServerAPI {
    @GET
    Call<ResponseBody> downlload(@Url String fileUrl);

    Retrofit retrofit =
            new Retrofit.Builder()
                    .baseUrl("http://192.168.43.135/retro/") 
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

}

public void download(){
    ServerAPI api = ServerAPI.retrofit.create(ServerAPI.class);
    api.downlload("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png").enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            try {
                File path = Environment.getExternalStorageDirectory();
                File file = new File(path, "file_name.jpg");
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                IOUtils.write(response.body().bytes(), fileOutputStream);
            }
            catch (Exception ex){
            }
        }


        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
        }
    });
}

如果可以,请指导我。 感谢

4 个答案:

答案 0 :(得分:12)

您需要创建一个特定的OkHttp客户端,它将拦截网络请求并发送更新。此客户端只应用于下载。

首先你需要一个接口,比如这个:

public interface OnAttachmentDownloadListener {
    void onAttachmentDownloadedSuccess();
    void onAttachmentDownloadedError();
    void onAttachmentDownloadedFinished();
    void onAttachmentDownloadUpdate(int percent);
}

您的下载调用应该返回ResponseBody,我们将从中扩展以便能够获得下载进度。

private static class ProgressResponseBody extends ResponseBody {

    private final ResponseBody responseBody;
    private final OnAttachmentDownloadListener progressListener;
    private BufferedSource bufferedSource;

    public ProgressResponseBody(ResponseBody responseBody, OnAttachmentDownloadListener progressListener) {
        this.responseBody = responseBody;
        this.progressListener = progressListener;
    }

    @Override public MediaType contentType() {
        return responseBody.contentType();
    }

    @Override public long contentLength() {
        return responseBody.contentLength();
    }

    @Override public BufferedSource source() {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    private Source source(Source source) {
        return new ForwardingSource(source) {
            long totalBytesRead = 0L;

            @Override public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);

                totalBytesRead += bytesRead != -1 ? bytesRead : 0;

                float percent = bytesRead == -1 ? 100f : (((float)totalBytesRead / (float) responseBody.contentLength()) * 100);

                if(progressListener != null)
                    progressListener.onAttachmentDownloadUpdate((int)percent);

                return bytesRead;
            }
        };
    }
}

然后你需要像这样创建你的OkHttpClient

public OkHttpClient.Builder getOkHttpDownloadClientBuilder(OnAttachmentDownloadListener progressListener) {
    OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();

    // You might want to increase the timeout
    httpClientBuilder.connectTimeout(20, TimeUnit.SECONDS);
    httpClientBuilder.writeTimeout(0, TimeUnit.SECONDS);
    httpClientBuilder.readTimeout(5, TimeUnit.MINUTES);

    httpClientBuilder.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            if(progressListener == null) return chain.proceed(chain.request());

        Response originalResponse = chain.proceed(chain.request());
        return originalResponse.newBuilder()
                .body(new ProgressResponseBody(originalResponse.body(), progressListener))
                .build();
        }
    });

    return httpClientBuilder;
}

最后,您只需通过传递新的OkHttp客户端,以不同的方式创建您的Retrofit客户端。根据您的代码,您可以使用以下内容:

 public Retrofit getDownloadRetrofit(OnAttachmentDownloadListener listener) {

    return new Retrofit.Builder()
                .baseUrl("http://192.168.43.135/retro/") 
                .addConverterFactory(GsonConverterFactory.create())
                .client(getOkHttpDownloadClientBuilder(listener).build())
                .build();

}

您的听众将处理您的通知的创建或其他任何您想要的内容。

答案 1 :(得分:4)

这是我与科特林的协程的变种

  1. 指定API接口。我们需要@Streaming注释来表示要手动处理响应主体的Retrofit。否则,改造将尝试将文件直接写入RAM
interface Api {

    @Streaming
    @GET("get-zip-ulr/{id}")
    fun getZip(@Path("id") id: Int): Call<ResponseBody>
}
  1. 创建将控制下载过程的数据源
class FilesDataSource(private val parentFolder: File, private val api: Api) {

    suspend fun downloadZip(id: Int, processCallback: (Long, Long) -> Unit): File {
        val response = api.getZip(id).awaitResponse()// returns the response, but it's content will be later
        val body = response.body()
        if (response.isSuccessful && body != null) {
            val file = File(parentFolder, "$id")
            body.byteStream().use { inputStream ->
                FileOutputStream(file).use { outputStream ->
                    val data = ByteArray(8192)
                    var read: Int
                    var progress = 0L
                    val fileSize = body.contentLength()
                    while (inputStream.read(data).also { read = it } != -1) {
                        outputStream.write(data, 0, read)
                        progress += read
                        publishProgress(processCallback, progress, fileSize)
                    }
                    publishProgress(processCallback, fileSize, fileSize)
                }
            }
            return file
        } else {
            throw HttpException(response)
        }
    }

    private suspend fun publishProgress(
        callback: (Long, Long) -> Unit,
        progress: Long, //bytes
        fileSize: Long  //bytes
    ) {
        withContext(Dispatchers.Main) { // invoke callback in UI thtread
            callback(progress, fileSize)
        }
    }
}

现在,您可以在downloadZip()ViewModel中执行Presenter方法并为其提供回调,该回调将链接到某些ProgerssBar。下载完成后,您将收到下载的文件。

答案 2 :(得分:2)

这是另一个使用 Flow 的 Kotlin 解决方案

interface MyService {
    @Streaming // allows streaming data directly to fs without holding all contents in ram
    @GET
    suspend fun getUrl(@Url url: String): ResponseBody
}

sealed class Download {
    data class Progress(val percent: Int) : Download()
    data class Finished(val file: File) : Download()
}

fun ResponseBody.downloadToFileWithProgress(directory: File, filename: String): Flow<Download> =
    flow {
        emit(Download.Progress(0))

        // flag to delete file if download errors or is cancelled
        var deleteFile = true
        val file = File(directory, "${filename}.${contentType()?.subtype}")

        try {
            byteStream().use { inputStream ->
                file.outputStream().use { outputStream ->
                    val totalBytes = contentLength()
                    val data = ByteArray(8_192)
                    var progressBytes = 0L

                    while (true) {
                        val bytes = inputStream.read(data)

                        if (bytes == -1) {
                            break
                        }

                        outputStream.channel
                        outputStream.write(data, 0, bytes)
                        progressBytes += bytes

                        emit(Download.Progress(percent = ((progressBytes * 100) / totalBytes).toInt()))
                    }

                    when {
                        progressBytes < totalBytes ->
                            throw Exception("missing bytes")
                        progressBytes > totalBytes ->
                            throw Exception("too many bytes")
                        else ->
                            deleteFile = false
                    }
                }
            }

            emit(Download.Finished(file))
        } finally {
            // check if download was successful

            if (deleteFile) {
                file.delete()
            }
        }
    }
        .flowOn(Dispatchers.IO)
        .distinctUntilChanged()

suspend fun Context.usage() {
    coroutineScope {
        myService.getUrl("https://www.google.com")
            .downloadToFileWithProgress(
                externalCacheDir!!,
                "my_file",
            )
            .collect { download ->
                when (download) {
                    is Download.Progress -> {
                        // update ui with progress
                    }
                    is Download.Finished -> {
                        // update ui with file
                    }
                }
            }
    }
}

答案 3 :(得分:0)

你可以看一下here,你不必自己实现它,背后的想法是获取请求的内容长度,当你在缓冲区上写时只计算你的进度