Giter Site home page Giter Site logo

jessyancoding / progressmanager Goto Github PK

View Code? Open in Web Editor NEW
2.7K 50.0 291.0 21.13 MB

⏳ Listen the progress of downloading and uploading in Okhttp, compatible Retrofit and Glide (一行代码即可监听 App 中所有网络链接的上传以及下载进度, 包括 Glide 的图片加载进度).

License: Apache License 2.0

Java 100.00%
okhttp glide retrofit listen receiver progress mvparms arms

progressmanager's Introduction

ProgressManager

Jcenter Build Status Android Arsenal API License Author QQ-Group

Listen the progress of downloading and uploading in Okhttp (compatible Retrofit and Glide).

中文说明

Overview

gif

Introduction

ProgressManager a line of code to listen App all the links and upload the progress of the network, including Glide picture loading progress, to achieve the principle of similar EventBus, you can be in anywhere in App, the number of listeners to Url address as an identifier, registered to the framework, when this Url address haves to download or upload the action, the framework will take the initiative to call All listeners registered with this Url address are synchronized to multiple modules.

Feature

  • Easy to use, just a line of code to listen progress.
  • Multi-platform support, support Okhttp , Retrofit , Glide ,Use Okhttp native Api , there is no compatibility problem.
  • Low coupling, the actual request and the progress of the receiver does not exist directly or indirectly, that can be anywhere in App to receive progress information.
  • Low intrusion, use this framework you do not need to change the code before uploading or downloading, ie using or not using this framework does not affect the original code.
  • Multi-end synchronization, the same data source upload or download progress can specify a number of different receivers, less to use EventBus achieve multiple port synchronization update progress.
  • Support multi-file upload.
  • Support URL redirection.
  • Automatic management of the listener, less to manually cancel the trouble of the listener.
  • The default run in the main line layer, less to switch the thread of trouble.
  • Lightweight framework, does not contain any three-party library, very small size.

Download

 implementation 'me.jessyan:progressmanager:1.5.0'

Usage

Step 1

 // When building OkHttpClient, the OkHttpClient.Builder() is passed to the with() method to initialize the configuration
 OkHttpClient = ProgressManager.getInstance().with(new OkHttpClient.Builder())
                .build();

Step 2

 // Glide load
 ProgressManager.getInstance().addResponseListener(IMAGE_URL, getGlideListener());


 // Okhttp/Retofit download
 ProgressManager.getInstance().addResponseListener(DOWNLOAD_URL, getDownloadListener());


 // Okhttp/Retofit upload
 ProgressManager.getInstance().addRequestListener(UPLOAD_URL, getUploadListener());

ProGuard

 -keep class me.jessyan.progressmanager.** { *; }
 -keep interface me.jessyan.progressmanager.** { *; }

About Me

License

 Copyright 2017, jessyan

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

progressmanager's People

Contributors

jessyancoding avatar tankcong avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

progressmanager's Issues

进度条

如果项目中下载资源的进度条不是你这个类型的。那么有没修改进度条的方法呢?

关于注册监听器回收的问题

你好,我看了一下您实现的源码里面,在ProgressManager.java这个类里面,对上传或者下载的ProgressListener统一放到WeakHashMap中进行处理。

此处,我想问,在注册了监听器后,因为WeakHashMap会对没有引用到的key,将其跟value一并回收了,所以在注册了监听器后的这段时间内,恰好GC回收,我觉得可能存在某些监听器也会被回收了,因为代码里面好像没看到哪里引用了这些key,所以我觉得有可能导致进度回调不了。

这是我的一点点疑问,也有可能我忽略了代码中某些重要地方,所以想问一下。

请教下Response.contentLength的获取

请教下,对于一些文件下载的Response,返回带Transfer-Encoding:chunked,没有Conntent-Length,这种情况下怎么获取文件大小contentLength?

上传

如果想要上传图片。是多张图片。同时还有文本参数。使用你的库可以嘛?没有找到传参的地方。

viewpager+photovie进度错乱

我在viewpager+photoview监听进度是 progressbar的进度错乱 进度一会大一会小 知道什么原因造成的

使用retrofit上传无法监听

下载监听是没问题的,但是上传怎样都无法监听的,我对照源码也配置了okhttp的client,val builder = ProgressManager.getInstance().with(OkHttpClient.Builder()),但是就是不管怎样都监听不到上传进度

ProgressListener的onError方法为什么不在主线程回调

在ProgressRequestBody和ProgressResponseBody里,只有成功的时候才是主线程,但是错误的的时候却只是回调出来,没做线程切换处理。
demo中是在activity创建一个Handler,然后在listener的onError中切换到主线程更新UI。这样会导致使用到上传的界面都需要创建Handler处理onError的回调。

Retrofit issue!

I'm using retrofit and creating instance of retrofit in this way.so how should I instantiate now?

private static final String BASE_URL = "base url";
public static Retrofit retrofit = null;

public static Retrofit getClient(){
    if(retrofit==null){
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new LoggingInterceptor()).build();

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

    }
    return retrofit;
}

弱引用问题

WeakHashMap是对Key进行弱引用,并不是对Value吧

现在版本是不支持Stick的吗?

就是我在请求发起后,再去添加监听,是不会执行后来加进来的监听。

protected Handler mHandler;
    protected int mRefreshTime;
    protected final ResponseBody mDelegate;
    protected final ProgressListener[] mListeners;
    protected final ProgressInfo mProgressInfo;
    private BufferedSource mBufferedSource;

    public ProgressResponseBody(Handler handler, ResponseBody responseBody, List<ProgressListener> listeners, int refreshTime) {
        this.mDelegate = responseBody;
        this.mListeners = listeners.toArray(new ProgressListener[listeners.size()]);
        this.mHandler = handler;
        this.mRefreshTime = refreshTime;
        this.mProgressInfo = new ProgressInfo(System.currentTimeMillis());
    }

这是我修改后的代码,是可以监听的,希望提供更优雅的解决方法

protected Handler mHandler;
    protected int mRefreshTime;
    protected final ResponseBody mDelegate;
    protected List<ProgressListener>  mListeners;
    protected final ProgressInfo mProgressInfo;
    private BufferedSource mBufferedSource;

    public ProgressResponseBody(Handler handler, ResponseBody responseBody, List<ProgressListener> listeners, int refreshTime) {
        this.mDelegate = responseBody;
        this.mListeners = listeners;
        this.mHandler = handler;
        this.mRefreshTime = refreshTime;
        this.mProgressInfo = new ProgressInfo(System.currentTimeMillis());
    }

下载进度完成会重复回调

image
通过progressInfo.getContentLength() == progressInfo.getCurrentbytes()这样判断下载完成,最后两次回调结果是相同的,这样会走两次下载完成的逻辑

contentLength=-1

我抄网上别的办法也是-1,所以试试这个。然后发现还是-1,所以在这里提问请教一下。

重定向后,新增进WeakHashMap中entry的回收问题

你好~ 重定向后,会根据重定向的地址新增相关的entry进WeakHashMap中以保证重定向后也可以监听进度,但是新增的entry的key值并没返回给activity或其他实现了listener的类,没返回的话就没办法在退出时置null,不置null的话WeakHashMap中相关的entry没被回收,没被回收就导致了内存泄漏。这样的说法有问题吗?

关于FormBody上传Base64的问题

  • 请问使用FormBody作为请求体的Post请求上传转成base64字符串的图片可以监听进度吗?
    我尝试发现进度总是一次就完成,contentLength大约在1M左右。

  • 另外就是关于上传进度的问题,在模拟弱网的测试下,上传进度已经完成,但是等待response超时,这样图片算是上传成功吗?

建议增加和Glide类似的方式二次监听相同的url方式

如下
public void addResponseListener(String url, ProgressListener listener) {
List progressListeners;
synchronized (ProgressManager.class) {
progressListeners = mResponseListeners.get(url);
if (progressListeners == null) {
progressListeners = new LinkedList<>();
mResponseListeners.put(url, progressListeners);
}
}
progressListeners.add(listener);
}
,这里我看到接收到相同的url时,直接把之前的progressListeners重新放到监听了,我觉得可以再增加一个方法,逻辑上是先删除之前已有的,再把新的加进去,具体使用哪个让开发者自由选择

为什么不开放mRequestListeners

例如这样子的一个需求,我从One Activity 监听进度,,打开了TwoActivity开始Service上传,然后 退出TwoActivity,再退出了OneActivity,,,这时候我再进去OneActivity,,怎么获取正在上传的进度???

我看了源码,接口在 mRequestListeners里面,但是并没有开放出来。

如果我不想要多个监听器,应该怎么样操作呢?

有个需求是这样子的,下载监听只要一个 ,,但是现在的情况是这样子的,应用会因为某些原因会重复addResponseListener相同的url,这样子就会导致onProgress同时回调多次,,但是我想只回调后面那一次。

我在demo把addResponseListener复制多了一行,然后下载的时候,onProgress每次回调都会回调两次,我是想覆盖的。但是addResponseListener并没有覆盖的

ProgressManager#haveRedirect方法实现

目前的ProgressManager#haveRedirect方法实现如下:

    private boolean haveRedirect(Response response) {
        String status = String.valueOf(response.code());
        if (TextUtils.isEmpty(status))
            return false;
        if (status.contains("301") || status.contains("302") || status.contains("303") || status.contains("307")) {
            return true;
        }
        return false;
    }

请问这里为什么不直接返回response#isRedirect ?

    private boolean haveRedirect(Response response) {
        return response.isRedirect();
    }

下面是Response#isRedirect的实现

 public boolean isRedirect() {
    switch (code) {
      case HTTP_PERM_REDIRECT:
      case HTTP_TEMP_REDIRECT:
      case HTTP_MULT_CHOICE:
      case HTTP_MOVED_PERM:
      case HTTP_MOVED_TEMP:
      case HTTP_SEE_OTHER:
        return true;
      default:
        return false;
    }
  }

跟默认的实现比起来,少了对308状态码(禁止UA改变原始请求METHOD)的处理,同时采用hardcode方式引入的状态码也不是很优雅。
期待您的回复,感谢您的贡献:)

比较急,关于Glide第二次加载同一张图片,因为Glide做了缓存,没有走进度回调的问题

如果是Glide第一次加载图片,一切运行正常,进度回调能够正常执行
不过我第二次打开我的界面,因为glide已经加载过一次了,glide默认对图片做了缓存,这样导致直接不走进度回调,因为我需要 进度回调 来操作我UI界面上的一些空间,显示或者不显示,比如操作progressbar的现实与隐藏,由于不走回调,我的progressbar只能一直显示在界面上。
我看你的DEMO代码里,加载图片不做缓存,这样演示确实比较方便,可是,一个项目的图片还是要做缓存的吧,,,这是你的演示代码
Glide.with(this)
.load(IMAGE_URL)
.centerCrop()
.placeholder(R.color.colorPrimary)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(mImageView);
求助?在Glide第二次加载图片的时候,我该如何控制我的progressbar的显示与隐藏?

我这样使用时发现内存泄漏情况

`Class Name | Shallow Heap | Retained Heap

cn.kuwo.boom.ui.make.ClipsHotPicFragment @ 0x1300cc88 | 280 | 1,536
'- this$0 cn.kuwo.boom.ui.make.ClipsHotPicFragment$2 @ 0x1300cc28 | 16 | 16
'- val$listener cn.kuwo.boom.http.down.Downloader$1 @ 0x1300cc18 | 16 | 32
'- item java.util.LinkedList$Node @ 0x1300cc00 | 24 | 56
'- first, last java.util.LinkedList @ 0x1300cbe8 | 24 | 80
'- value java.util.WeakHashMap$Entry @ 0x1300cbc0 | 40 | 216
'- [7] java.util.WeakHashMap$Entry[16] @ 0x1300cb70 | 80 | 296
'- table java.util.WeakHashMap @ 0x1300cb28 | 48 | 376
'- mResponseListeners me.jessyan.progressmanager.ProgressManager @ 0x1300cab8 | 32 | 600
|- mProgressManager class me.jessyan.progressmanager.ProgressManager @ 0x12e2b8f8 System Class, Native Stack| 32 | 168
|- this$0 me.jessyan.progressmanager.ProgressManager$1 @ 0x1300caa0 | 16 | 16
'- Total: 2 entries | |

`

使用方式
`ProgressManager.getInstance().addResponseListener(url, new ProgressListener(){

        @Override
        public void onProgress(ProgressInfo progressInfo) {
            Log.d(TAG, "file download: " + progressInfo.getCurrentbytes() + " of " + progressInfo.getContentLength());
            if(listener!=null){
                listener.onDownloadProcess(url,progressInfo.getPercent());
            }
        }

        @Override
        public void onError(long id, Exception e) {
            Log.d(TAG,"error:"+e.getMessage());
            if (listener != null) {
                listener.onDownloadFailed(url, -2, "" + e.getMessage());
            }
        }
    });`

自定义的ImageView里面设置图片监听导致内存泄漏,该如何避免呢?

/**
* 设置加载网路图片
*
* @param imageUrl
*/
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
//getGlideLoadListener(imageUrl); TODO 此处这样使用会导致内存泄漏
GlideImageUtil.showImage(imageUrl, this);
}

/**
 * okhttp/Retofit 图片加载监听
 */
private void getGlideLoadListener(String imageUrl) {
    ProgressManager.getInstance().addResponseListener(imageUrl, new ProgressListener() {
        @Override
        public void onProgress(ProgressInfo progressInfo) {
            LogUtil.i("rudni_图片加载进度", "已加载:" + progressInfo.getPercent());
            if (progressInfo.isFinish()) {
                LogUtil.i("rudni_图片加载进度", "加载完成");
            }
        }

        @Override
        public void onError(long id, Exception e) {
            LogUtil.i("rudni_图片加载进度", "图片加载失败:" + e.getMessage());
        }
    });
}

使用retrofit上传文件监听问题

在某个界面选择文件上传,能显示进度条进度,这时候取消上传,在选择该文件上传,也能显示进度条进度,但是当取消上传后退出该界面,在进入页面选择该文件上传时进度条不起作用。请问这个怎么解决?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.