Skip to content

Commit

Permalink
Add notifyOnErorr
Browse files Browse the repository at this point in the history
  • Loading branch information
JessYanCoding committed Jun 13, 2017
1 parent 21faede commit 991e453
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,8 @@ public void run() {
response.body();
} catch (IOException e) {
e.printStackTrace();
//当外部发生错误时,使用此方法可以通知所有监听器的 onError 方法
ProgressManager.getInstance().notifyOnErorr(UPLOAD_URL, e);
}
}
}).start();
Expand All @@ -239,14 +241,14 @@ public void run() {
* 点击开始下载资源,为了演示,就不做重复点击的处理,即允许用户在还有进度没完成的情况下,使用同一个 url 开始新的下载
*/
private void downloadStart() {
final Request request = new Request.Builder()
.url(DOWNLOAD_URL)
.build();

new Thread(new Runnable() {
@Override
public void run() {
try {
Request request = new Request.Builder()
.url(DOWNLOAD_URL)
.build();

Response response = mOkHttpClient.newCall(request).execute();

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

} catch (IOException e) {
e.printStackTrace();
//当外部发生错误时,使用此方法可以通知所有监听器的 onError 方法
ProgressManager.getInstance().notifyOnErorr(DOWNLOAD_URL, e);
}
}
}).start();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,21 @@ public void addResponseListener(String url, ProgressListener listener) {
progressListeners.add(listener);
}


/**
* 当在 {@link ProgressRequestBody} 和 {@link ProgressResponseBody} 内部处理二进制流时发生错误
* 会主动调用 {@link ProgressListener#onError(long, Exception)},但是有些错误并不是在它们内部发生的
* 但同样会引起网络请求的失败,所以向外面提供{@link ProgressManager#notifyOnErorr},当外部发生错误时
* 手动调用此方法,以通知所有的监听器
*
* @param url
* @param e
*/
public void notifyOnErorr(String url, Exception e) {
forEachListenersOnError(mRequestListeners, url, e);
forEachListenersOnError(mResponseListeners, url, e);
}

/**
* 将 {@link okhttp3.OkHttpClient.Builder} 传入,配置一些本管理器需要的参数
*
Expand Down Expand Up @@ -164,4 +179,15 @@ public Response wrapResponseBody(Response response) {
return response;
}


private void forEachListenersOnError(Map<String, List<ProgressListener>> map, String url, Exception e) {
if (map.containsKey(url)) {
List<ProgressListener> progressListeners = map.get(url);
ProgressListener[] array = progressListeners.toArray(new ProgressListener[progressListeners.size()]);
for (int i = 0; i < array.length; i++) {
array[i].onError(-1, e);
}
}
}

}

0 comments on commit 991e453

Please sign in to comment.