Skip to content

Instantly share code, notes, and snippets.

@li2
Last active March 20, 2018 11:50
Show Gist options
  • Save li2/252e6c7dfd0d0910347065efcf11c9e3 to your computer and use it in GitHub Desktop.
Save li2/252e6c7dfd0d0910347065efcf11c9e3 to your computer and use it in GitHub Desktop.
[Is it possible to show progress bar when upload image via Retrofit 2?] http://stackoverflow.com/questions/33338181/is-it-possible-to-show-progress-bar-when-upload-image-via-retrofit-2/33384551#33384551 #tags: android-network
public class ProgressRequestBody extends RequestBody {
private File mFile;
private String mPath;
private UploadCallbacks mListener;
private static final int DEFAULT_BUFFER_SIZE = 2048;
public interface UploadCallbacks {
void onProgressUpdate(int percentage);
void onError();
void onFinish();
}
public ProgressRequestBody(final File file, final UploadCallbacks listener) {
mFile = file;
mListener = listener;
}
@Override
public MediaType contentType() {
// i want to upload only images
return MediaType.parse("image/*");
}
@Override
public long contentLength() throws IOException {
return mFile.length();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
long fileLength = mFile.length();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
FileInputStream in = new FileInputStream(mFile);
long uploaded = 0;
try {
int read;
Handler handler = new Handler(Looper.getMainLooper());
while ((read = in.read(buffer)) != -1) {
// update progress on UI thread
handler.post(new ProgressUpdater(uploaded, fileLength));
uploaded += read;
sink.write(buffer, 0, read);
}
} finally {
in.close();
}
}
private class ProgressUpdater implements Runnable {
private long mUploaded;
private long mTotal;
public ProgressUpdater(long uploaded, long total) {
mUploaded = uploaded;
mTotal = total;
}
@Override
public void run() {
mListener.onProgressUpdate((int)(100 * mUploaded / mTotal));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment