Android Retrofit - onProgressUpdate for showing Progress Notification

后端 未结 2 610
情话喂你
情话喂你 2020-11-28 19:46

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 sim

2条回答
  •  一生所求
    2020-11-28 20:07

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

    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();
            }
        }
    }
    

提交回复
热议问题