Android Retrofit - onProgressUpdate 用于显示进度通知

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23348812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:02:11  来源:igfitidea点击:

Android Retrofit - onProgressUpdate for showing Progress Notification

androidandroid-asynctaskretrofit

提问by John Shelley

I'm currently using Retrofit by Square for Android network communications. Is there a way to get its progress during a task to create a progress notification, something similar to that which Facebook uses when uploading an image?

我目前正在使用 Square 的 Retrofit 进行 Android 网络通信。有没有办法在任务期间获取进度以创建进度通知,类似于 Facebook 在上传图像时使用的通知?

Use Case would be to load an image hopefully of full image quality without compression or scaling.

用例是在不压缩或缩放的情况下加载希望具有完整图像质量的图像。

I see how it is possible with an asynctask but that would defeat the purpose of using Retrofit. However that might be the route I would have to take.

我看到 asynctask 是如何可能的,但这会破坏使用 Retrofit 的目的。然而,这可能是我必须走的路线。

回答by Davi Alves

This answer is for Retrofit 1. For solution compatible with Retrofit 2 see this answer.

此答案适用于 Retrofit 1。有关与 Retrofit 2 兼容的解决方案,请参阅此答案



I had the same problem and finally managed to do it. I was using spring lib before and what I show below kind worked for Spring but was inconsistent since I made a mistake on using it for the InputStream. I moved all my API's to use retrofit and upload was the last one on the list, I just override TypedFilewriteTo() to update me on the bytes read to the OutputStream. Maybe this can be improved but as I said I made it when I was using Spring so I just reused it. This is the code for upload and it's working for me on my app, if you want download feedback then you can use @Streaming and read the inputStream.

我遇到了同样的问题,最后设法做到了。我之前使用过 spring lib,我在下面展示的内容适用于 Spring,但不一致,因为我在将它用于 InputStream 时犯了一个错误。我移动了我所有的 API 来使用改造,上传是列表中的最后一个,我只是覆盖了TypedFilewriteTo() 来更新我读取到 OutputStream 的字节。也许这可以改进,但正如我所说,我是在使用 Spring 时制作的,所以我只是重用了它。这是上传代码,它在我的应用程序上对我有用,如果你想要下载反馈,那么你可以使用@Streaming 并阅读 inputStream。

ProgressListener

进度监听器

public interface ProgressListener {
 void transferred(long num);
}

CountingTypedFile

计数类型文件

public class CountingTypedFile extends TypedFile {

 private static final int BUFFER_SIZE = 4096;

 private final ProgressListener listener;

 public CountingTypedFile(String mimeType, File file, ProgressListener listener) {
    super(mimeType, file);
    this.listener = listener;
 }

 @Override public void writeTo(OutputStream out) throws IOException {
    byte[] buffer = new byte[BUFFER_SIZE];
    FileInputStream in = new FileInputStream(super.file());
    long total = 0;
    try {
        int read;
        while ((read = in.read(buffer)) != -1) {
            total += read;
            this.listener.transferred(total);
            out.write(buffer, 0, read);
        }
    } finally {
        in.close();
    }
 }
}

MyApiService

我的服务

public interface MyApiService {
 @Multipart
 @POST("/files")
 ApiResult uploadFile(@Part("file") TypedFile resource, @Query("path") String path);
}

SendFileTask

发送文件任务

private class SendFileTask extends AsyncTask<String, Integer, ApiResult> {
    private ProgressListener listener;
    private String filePath;
    private FileType fileType;

    public SendFileTask(String filePath, FileType fileType) {
        this.filePath = filePath;
        this.fileType = fileType;
    }

    @Override
    protected ApiResult doInBackground(String... params) {
        File file = new File(filePath);
        totalSize = file.length();
        Logger.d("Upload FileSize[%d]", totalSize);
        listener = new ProgressListener() {
            @Override
            public void transferred(long num) {
                publishProgress((int) ((num / (float) totalSize) * 100));
            }
        };
        String _fileType = FileType.VIDEO.equals(fileType) ? "video/mp4" : (FileType.IMAGE.equals(fileType) ? "image/jpeg" : "*/*");
        return MyRestAdapter.getService().uploadFile(new CountingTypedFile(_fileType, file, listener), "/Mobile Uploads");
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        Logger.d(String.format("progress[%d]", values[0]));
        //do something with values[0], its the percentage so you can easily do
        //progressBar.setProgress(values[0]);
    }
}

The CountingTypedFileis just a copy of TypedFilebut including the ProgressListener.

CountingTypedFile只是一个副本TypedFile但包括ProgressListener。

回答by Gnzlt

If you want to get the max value in order to show it on a ProgressDialog, Notification, etc.

如果您想获得最大值以将其显示在 ProgressDialog、Notification 等中,请执行以下操作:

ProgressListener

进度监听器

public interface ProgressListener {
    void transferred(long num, long max);
}

CountingTypedFile

计数类型文件

public class CountingTypedFile extends TypedFile {

    private static final int BUFFER_SIZE = 4096;

    private final ProgressListener listener;

    public CountingTypedFile(String mimeType, File file, ProgressListener listener) {
        super(mimeType, file);
        this.listener = listener;
    }

    @Override
    public void writeTo(OutputStream out) throws IOException {
        byte[] buffer = new byte[BUFFER_SIZE];
        FileInputStream in = new FileInputStream(super.file());
        long total = 0;
        try {
            int read;
            while ((read = in.read(buffer)) != -1) {
                total += read;
                this.listener.transferred(total, super.file().length());
                out.write(buffer, 0, read);
            }
        } finally {
            in.close();
        }
    }
}