ProgressManager 中的LIst 改为 Map 是不是更好一点呢? url 做 key
ifmvo opened this issue · 0 comments
public class ProgressManager {
private static Map<String, WeakReference<OnProgressListener>> listenersMap = Collections.synchronizedMap(new HashMap<String, WeakReference<OnProgressListener>>());
private static OkHttpClient okHttpClient;
private ProgressManager() {
}
public static OkHttpClient getOkHttpClient() {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
return response.newBuilder()
.body(new ProgressResponseBody(request.url().toString(), response.body(), listenersMap.get(request.url().toString()).get()))
.build();
}
})
.build();
}
return okHttpClient;
}
// private static final OnProgressListener LISTENER = new OnProgressListener() {
// @OverRide
// public void onProgress(String imageUrl, long bytesRead, long totalBytes, boolean isDone, GlideException exception) {
// if (listenersMap == null || listenersMap.size() == 0) return;
// for (int i = 0; i < listenersMap.size(); i++) {
// WeakReference listener = listenersMap.get(i);
// OnProgressListener progressListener = listener.get();
// if (progressListener == null) {
// listenersMap.remove(i);
// } else {
// progressListener.onProgress(imageUrl, bytesRead, totalBytes, isDone, exception);
// }
// }
// }
// };
/**
* 使用URL做key 保存在map中
* @param key
* @param progressListener
*/
public static void addProgressListener(String key, OnProgressListener progressListener) {
if (progressListener == null || TextUtils.isEmpty(key)) return;
if (!listenersMap.containsKey(key)) {
listenersMap.put(key, new WeakReference<>(progressListener));
}
}
public static void removeProgressListener(String key, OnProgressListener progressListener) {
if (progressListener == null || TextUtils.isEmpty(key)) return;
listenersMap.remove(key);
}
// private static WeakReference findProgressListener(OnProgressListener listener) {
// if (listener == null) return null;
// if (listenersMap == null || listenersMap.size() == 0) return null;
//
// for (int i = 0; i < listenersMap.size(); i++) {
// WeakReference progressListener = listenersMap.get(i);
// if (progressListener.get() == listener) {
// return progressListener;
// }
// }
// return null;
// }
}