Skip to content

Commit 991e453

Browse files
committed
Add notifyOnErorr
1 parent 21faede commit 991e453

2 files changed

Lines changed: 34 additions & 4 deletions

File tree

app/src/main/java/me/jessyan/progressmanager/demo/MainActivity.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,8 @@ public void run() {
230230
response.body();
231231
} catch (IOException e) {
232232
e.printStackTrace();
233+
//当外部发生错误时,使用此方法可以通知所有监听器的 onError 方法
234+
ProgressManager.getInstance().notifyOnErorr(UPLOAD_URL, e);
233235
}
234236
}
235237
}).start();
@@ -239,14 +241,14 @@ public void run() {
239241
* 点击开始下载资源,为了演示,就不做重复点击的处理,即允许用户在还有进度没完成的情况下,使用同一个 url 开始新的下载
240242
*/
241243
private void downloadStart() {
242-
final Request request = new Request.Builder()
243-
.url(DOWNLOAD_URL)
244-
.build();
245-
246244
new Thread(new Runnable() {
247245
@Override
248246
public void run() {
249247
try {
248+
Request request = new Request.Builder()
249+
.url(DOWNLOAD_URL)
250+
.build();
251+
250252
Response response = mOkHttpClient.newCall(request).execute();
251253

252254
InputStream is = response.body().byteStream();
@@ -267,6 +269,8 @@ public void run() {
267269

268270
} catch (IOException e) {
269271
e.printStackTrace();
272+
//当外部发生错误时,使用此方法可以通知所有监听器的 onError 方法
273+
ProgressManager.getInstance().notifyOnErorr(DOWNLOAD_URL, e);
270274
}
271275
}
272276
}).start();

progress/src/main/java/me/jessyan/progressmanager/ProgressManager.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,21 @@ public void addResponseListener(String url, ProgressListener listener) {
111111
progressListeners.add(listener);
112112
}
113113

114+
115+
/**
116+
* 当在 {@link ProgressRequestBody} 和 {@link ProgressResponseBody} 内部处理二进制流时发生错误
117+
* 会主动调用 {@link ProgressListener#onError(long, Exception)},但是有些错误并不是在它们内部发生的
118+
* 但同样会引起网络请求的失败,所以向外面提供{@link ProgressManager#notifyOnErorr},当外部发生错误时
119+
* 手动调用此方法,以通知所有的监听器
120+
*
121+
* @param url
122+
* @param e
123+
*/
124+
public void notifyOnErorr(String url, Exception e) {
125+
forEachListenersOnError(mRequestListeners, url, e);
126+
forEachListenersOnError(mResponseListeners, url, e);
127+
}
128+
114129
/**
115130
* 将 {@link okhttp3.OkHttpClient.Builder} 传入,配置一些本管理器需要的参数
116131
*
@@ -164,4 +179,15 @@ public Response wrapResponseBody(Response response) {
164179
return response;
165180
}
166181

182+
183+
private void forEachListenersOnError(Map<String, List<ProgressListener>> map, String url, Exception e) {
184+
if (map.containsKey(url)) {
185+
List<ProgressListener> progressListeners = map.get(url);
186+
ProgressListener[] array = progressListeners.toArray(new ProgressListener[progressListeners.size()]);
187+
for (int i = 0; i < array.length; i++) {
188+
array[i].onError(-1, e);
189+
}
190+
}
191+
}
192+
167193
}

0 commit comments

Comments
 (0)