-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgressRequestBody.java
76 lines (58 loc) · 1.91 KB
/
ProgressRequestBody.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.example.myfile;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
public class ProgressRequestBody extends RequestBody {
private File file;
private UploadCallBacks listener;
private static final int DEFAULT_BUFFER_SIZE = 4096;
public ProgressRequestBody(File file, UploadCallBacks listener) {
this.file = file;
this.listener = listener;
}
@Nullable
@Override
public MediaType contentType() {
return MediaType.parse("/*");
}
@Override
public long contentLength() throws IOException {
return file.length();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
long fileLength = file.length();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
FileInputStream in = new FileInputStream(file);
long uploaded = 0;
try{
int read;
Handler handler = new Handler(Looper.getMainLooper());
while (( read = in.read(buffer)) != -1) {
handler.post(new ProgressUpdater(uploaded, fileLength));
uploaded += read;
sink.write(buffer, 0, read);
}
} finally {
in.close();
}
}
private class ProgressUpdater implements Runnable {
private long uploaded;
private long fileLength;
public ProgressUpdater(long uploaded, long fileLength) {
this.uploaded = uploaded;
this.fileLength = fileLength;
}
@Override
public void run() {
listener.onProgressUpdate((int) (100 * uploaded/fileLength));
}
}
}