├── .gitignore ├── .travis.yml ├── LICENSE ├── README-zh.md ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── me │ │ └── jessyan │ │ └── progressmanager │ │ └── demo │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── assets │ │ └── a.java │ ├── java │ │ └── me │ │ │ └── jessyan │ │ │ └── progressmanager │ │ │ └── demo │ │ │ ├── AdvanceActivity.java │ │ │ ├── AdvanceFragment.java │ │ │ ├── BaseApplication.java │ │ │ ├── GlideConfiguration.java │ │ │ ├── MainActivity.java │ │ │ └── MainFragment.java │ └── res │ │ ├── layout │ │ ├── activity_advance.xml │ │ ├── activity_main.xml │ │ └── fragment_main.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── me │ └── jessyan │ └── progressmanager │ └── demo │ └── ExampleUnitTest.java ├── arts └── progressManager.gif ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── progress ├── .gitignore ├── bintray.gradle ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── me │ │ └── jessyan │ │ └── progressmanager │ │ ├── ProgressListener.java │ │ ├── ProgressManager.java │ │ └── body │ │ ├── ProgressInfo.java │ │ ├── ProgressRequestBody.java │ │ └── ProgressResponseBody.java │ └── res │ └── values │ └── strings.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the ART/Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | out/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | 20 | # Local configuration file (sdk path, etc) 21 | local.properties 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | 26 | # Log Files 27 | *.log 28 | 29 | # Android Studio Navigation editor temp files 30 | .navigation/ 31 | 32 | # Android Studio captures folder 33 | captures/ 34 | 35 | # Intellij 36 | *.iml 37 | .idea 38 | 39 | # Keystore files 40 | *.jks 41 | 42 | # MacOS 43 | .DS_Store 44 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | jdk: oraclejdk8 3 | - yes | sdkmanager "platforms;android-27" 4 | 5 | env: 6 | global: 7 | - ANDROID_API_LEVEL=27 8 | - ANDROID_BUILD_TOOLS_VERSION=27.0.3 9 | - TRAVIS_SECURE_ENV_VARS=true 10 | 11 | android: 12 | components: 13 | # The BuildTools version used by your project 14 | - tools 15 | - platform-tools 16 | - build-tools-$ANDROID_BUILD_TOOLS_VERSION 17 | - extra-android-m2repository 18 | - extra-google-android-support 19 | 20 | # The SDK version used to compile your project 21 | - android-$ANDROID_API_LEVEL 22 | licenses: 23 | - '.+' 24 | 25 | script: 26 | - ./gradlew clean 27 | - ./gradlew assembleDebug 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README-zh.md: -------------------------------------------------------------------------------- 1 | # ProgressManager 2 | [ ![Jcenter](https://img.shields.io/badge/Jcenter-v1.5.0-brightgreen.svg?style=flat-square) ](https://bintray.com/jessyancoding/maven/progressmanager/1.5.0/link) 3 | [ ![Build Status](https://travis-ci.org/JessYanCoding/ProgressManager.svg?branch=master) ](https://travis-ci.org/JessYanCoding/ProgressManager) 4 | [ ![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-ProgressManager-brightgreen.svg?style=flat-square)](https://android-arsenal.com/details/1/5865) 5 | [ ![API](https://img.shields.io/badge/API-14%2B-blue.svg?style=flat-square) ](https://developer.android.com/about/versions/android-4.0.html) 6 | [ ![License](http://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat-square) ](http://www.apache.org/licenses/LICENSE-2.0) 7 | [ ![Author](https://img.shields.io/badge/Author-JessYan-orange.svg?style=flat-square) ](https://www.jianshu.com/u/1d0c0bc634db) 8 | [ ![QQ-Group](https://img.shields.io/badge/QQ%E7%BE%A4-455850365%20%7C%20301733278-orange.svg?style=flat-square) ](https://shang.qq.com/wpa/qunwpa?idkey=7e59e59145e6c7c68932ace10f52790636451f01d1ecadb6a652b1df234df753) 9 | 10 | 11 | ## Listen the progress of downloading and uploading in Okhttp (compatible Retrofit and Glide). 12 | 13 | 14 | ## Overview 15 | ![gif](arts/progressManager.gif) 16 | 17 | 18 | ## Introduction 19 | **ProgressManager** 一行代码即可监听 **App** 中所有网络链接的上传以及下载进度,包括 **Glide** 的图片加载进度,实现原理类似 **EventBus**,你可在 **App** 中的任何地方,将多个监听器,以 **Url** 地址作为标识符,注册到本框架,当此 **Url** 地址存在下载或者上传的动作时,框架会主动调用所有使用此 **Url** 地址注册过的监听器,达到多个模块的同步更新. 20 | 21 | > [**框架的构思和实现可以看这篇文章**](https://juejin.im/post/593d85e55c497d006b90433d) 22 | 23 | ## Feature 24 | * 使用简单,只需一行代码即可实现进度监听. 25 | * 多平台支持,支持 **Okhttp** , **Retrofit** , **Glide** ,使用 **Okhttp** 原生 **Api** ,不存在兼容问题. 26 | * 低耦合,实际请求端和进度接收端并不存在直接或间接的关联关系,即可以在 **App** 任何地方接收进度信息. 27 | * 侵入性低,使用本框架你并不需要更改之前进行上传或下载的代码,即使用或不使用本框架并不会影响到原有的代码. 28 | * 多端同步,同一个数据源的上传或下载进度可以指定多个不同的接收端,少去了使用 **EventBus** 实现多个端口同步更新进度. 29 | * 支持多文件上传. 30 | * 支持 **URL** 重定向. 31 | * 自动管理监听器,少去了手动注销监听器的烦恼. 32 | * 默认运行在主线层,少去了切换线程的烦恼. 33 | * 轻量级框架,不包含任何三方库,体积极小. 34 | 35 | ## Download 36 | ``` gradle 37 | implementation 'me.jessyan:progressmanager:1.5.0' 38 | ``` 39 | 40 | ## Usage 41 | ### Step 1 42 | ``` java 43 | // 构建 OkHttpClient 时,将 OkHttpClient.Builder() 传入 with() 方法,进行初始化配置 44 | OkHttpClient = ProgressManager.getInstance().with(new OkHttpClient.Builder()) 45 | .build(); 46 | ``` 47 | 48 | ### Step 2 49 | ``` java 50 | // Glide 下载监听 51 | ProgressManager.getInstance().addResponseListener(IMAGE_URL, getGlideListener()); 52 | 53 | 54 | // Okhttp/Retofit 下载监听 55 | ProgressManager.getInstance().addResponseListener(DOWNLOAD_URL, getDownloadListener()); 56 | 57 | 58 | // Okhttp/Retofit 上传监听 59 | ProgressManager.getInstance().addRequestListener(UPLOAD_URL, getUploadListener()); 60 | ``` 61 | 62 | 63 | ## ProGuard 64 | ``` 65 | -keep class me.jessyan.progressmanager.** { *; } 66 | -keep interface me.jessyan.progressmanager.** { *; } 67 | ``` 68 | 69 | ## About Me 70 | * **Email**: 71 | * **Home**: 72 | * **掘金**: 73 | * **简书**: 74 | 75 | ## License 76 | ``` 77 | Copyright 2017, jessyan 78 | 79 | Licensed under the Apache License, Version 2.0 (the "License"); 80 | you may not use this file except in compliance with the License. 81 | You may obtain a copy of the License at 82 | 83 | http://www.apache.org/licenses/LICENSE-2.0 84 | 85 | Unless required by applicable law or agreed to in writing, software 86 | distributed under the License is distributed on an "AS IS" BASIS, 87 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 88 | See the License for the specific language governing permissions and 89 | limitations under the License. 90 | ``` 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ProgressManager 2 | [ ![Jcenter](https://img.shields.io/badge/Jcenter-v1.5.0-brightgreen.svg?style=flat-square) ](https://bintray.com/jessyancoding/maven/progressmanager/1.5.0/link) 3 | [ ![Build Status](https://travis-ci.org/JessYanCoding/ProgressManager.svg?branch=master) ](https://travis-ci.org/JessYanCoding/ProgressManager) 4 | [ ![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-ProgressManager-brightgreen.svg?style=flat-square)](https://android-arsenal.com/details/1/5865) 5 | [ ![API](https://img.shields.io/badge/API-14%2B-blue.svg?style=flat-square) ](https://developer.android.com/about/versions/android-4.0.html) 6 | [ ![License](http://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat-square) ](http://www.apache.org/licenses/LICENSE-2.0) 7 | [ ![Author](https://img.shields.io/badge/Author-JessYan-orange.svg?style=flat-square) ](https://www.jianshu.com/u/1d0c0bc634db) 8 | [ ![QQ-Group](https://img.shields.io/badge/QQ%E7%BE%A4-455850365%20%7C%20301733278-orange.svg?style=flat-square) ](https://shang.qq.com/wpa/qunwpa?idkey=7e59e59145e6c7c68932ace10f52790636451f01d1ecadb6a652b1df234df753) 9 | 10 | 11 | ## Listen the progress of downloading and uploading in Okhttp (compatible Retrofit and Glide). 12 | 13 | [中文说明](README-zh.md) 14 | 15 | ## Overview 16 | ![gif](arts/progressManager.gif) 17 | 18 | ## Introduction 19 | **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. 20 | 21 | 22 | ## Feature 23 | * Easy to use, just a line of code to listen progress. 24 | * Multi-platform support, support **Okhttp** , **Retrofit** , **Glide** ,Use **Okhttp** native **Api** , there is no compatibility problem. 25 | * 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. 26 | * 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. 27 | * 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. 28 | * Support multi-file upload. 29 | * Support **URL** redirection. 30 | * Automatic management of the listener, less to manually cancel the trouble of the listener. 31 | * The default run in the main line layer, less to switch the thread of trouble. 32 | * Lightweight framework, does not contain any three-party library, very small size. 33 | 34 | ## Download 35 | ``` gradle 36 | implementation 'me.jessyan:progressmanager:1.5.0' 37 | ``` 38 | 39 | ## Usage 40 | ### Step 1 41 | ``` java 42 | // When building OkHttpClient, the OkHttpClient.Builder() is passed to the with() method to initialize the configuration 43 | OkHttpClient = ProgressManager.getInstance().with(new OkHttpClient.Builder()) 44 | .build(); 45 | ``` 46 | 47 | ### Step 2 48 | ``` java 49 | // Glide load 50 | ProgressManager.getInstance().addResponseListener(IMAGE_URL, getGlideListener()); 51 | 52 | 53 | // Okhttp/Retofit download 54 | ProgressManager.getInstance().addResponseListener(DOWNLOAD_URL, getDownloadListener()); 55 | 56 | 57 | // Okhttp/Retofit upload 58 | ProgressManager.getInstance().addRequestListener(UPLOAD_URL, getUploadListener()); 59 | ``` 60 | 61 | 62 | ## ProGuard 63 | ``` 64 | -keep class me.jessyan.progressmanager.** { *; } 65 | -keep interface me.jessyan.progressmanager.** { *; } 66 | ``` 67 | 68 | ## About Me 69 | * **Email**: 70 | * **Home**: 71 | * **掘金**: 72 | * **简书**: 73 | 74 | ## License 75 | ``` 76 | Copyright 2017, jessyan 77 | 78 | Licensed under the Apache License, Version 2.0 (the "License"); 79 | you may not use this file except in compliance with the License. 80 | You may obtain a copy of the License at 81 | 82 | http://www.apache.org/licenses/LICENSE-2.0 83 | 84 | Unless required by applicable law or agreed to in writing, software 85 | distributed under the License is distributed on an "AS IS" BASIS, 86 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 87 | See the License for the specific language governing permissions and 88 | limitations under the License. 89 | ``` 90 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion rootProject.compileSdkVersion 5 | buildToolsVersion rootProject.buildToolsVersion 6 | defaultConfig { 7 | applicationId "me.jessyan.progressmanager.demo" 8 | minSdkVersion rootProject.minSdkVersion 9 | targetSdkVersion rootProject.targetSdkVersion 10 | versionCode rootProject.versionCode 11 | versionName rootProject.versionName 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | lintOptions { 21 | abortOnError false 22 | warning 'InvalidPackage' 23 | } 24 | } 25 | 26 | dependencies { 27 | implementation fileTree(dir: 'libs', include: ['*.jar']) 28 | testImplementation 'junit:junit:4.12' 29 | implementation 'com.android.support:appcompat-v7:27.1.1' 30 | implementation 'com.squareup.okhttp3:okhttp:3.10.0' 31 | implementation 'com.github.bumptech.glide:glide:4.6.1' 32 | annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1' 33 | implementation 'com.github.bumptech.glide:okhttp3-integration:4.6.1' 34 | implementation project(':progress') 35 | // implementation 'me.jessyan:progressmanager:1.5.0' 36 | } 37 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/jess/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Uncomment this to preserve the line number information for 20 | # debugging stack traces. 21 | #-keepattributes SourceFile,LineNumberTable 22 | 23 | # If you keep the line number information, uncomment this to 24 | # hide the original source file name. 25 | #-renamesourcefileattribute SourceFile 26 | -------------------------------------------------------------------------------- /app/src/androidTest/java/me/jessyan/progressmanager/demo/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package me.jessyan.progressmanager.demo; 2 | 3 | /** 4 | * Instrumentation test, which will execute on an Android device. 5 | * 6 | * @see Testing documentation 7 | */ 8 | public class ExampleInstrumentedTest { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 17 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /app/src/main/java/me/jessyan/progressmanager/demo/AdvanceActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package me.jessyan.progressmanager.demo; 17 | 18 | import android.os.Bundle; 19 | import android.os.Handler; 20 | import android.support.annotation.NonNull; 21 | import android.support.v7.app.AppCompatActivity; 22 | import android.util.Log; 23 | import android.view.View; 24 | import android.widget.ImageView; 25 | import android.widget.ProgressBar; 26 | import android.widget.TextView; 27 | 28 | import com.bumptech.glide.load.engine.DiskCacheStrategy; 29 | 30 | import java.io.BufferedInputStream; 31 | import java.io.File; 32 | import java.io.FileOutputStream; 33 | import java.io.IOException; 34 | import java.io.InputStream; 35 | 36 | import me.jessyan.progressmanager.ProgressListener; 37 | import me.jessyan.progressmanager.ProgressManager; 38 | import me.jessyan.progressmanager.body.ProgressInfo; 39 | import okhttp3.MediaType; 40 | import okhttp3.OkHttpClient; 41 | import okhttp3.Request; 42 | import okhttp3.RequestBody; 43 | import okhttp3.Response; 44 | 45 | /** 46 | * ================================================ 47 | * 这里为了展示本框架的高级功能,使用同一个 url 地址根据 Post 请求参数的不同而下载或上传不同的资源 48 | * 49 | * @see {@link #initListener} 50 | * Created by JessYan on 08/06/2017 12:59 51 | * Contact me 52 | * Follow me 53 | * ================================================ 54 | */ 55 | public class AdvanceActivity extends AppCompatActivity implements View.OnClickListener { 56 | private static final String TAG = "AdvanceActivity"; 57 | private ImageView mImageView; 58 | private OkHttpClient mOkHttpClient; 59 | private ProgressBar mGlideProgress; 60 | private ProgressBar mDownloadProgress; 61 | private ProgressBar mUploadProgress; 62 | private TextView mGlideProgressText; 63 | private TextView mDownloadProgressText; 64 | private TextView mUploadProgressText; 65 | 66 | private ProgressInfo mLastDownloadingInfo; 67 | private ProgressInfo mLastUploadingingInfo; 68 | private Handler mHandler; 69 | private String mNewImageUrl; 70 | private String mNewDownloadUrl; 71 | private String mNewUploadUrl; 72 | 73 | 74 | @Override 75 | protected void onCreate(Bundle savedInstanceState) { 76 | super.onCreate(savedInstanceState); 77 | mOkHttpClient = ((BaseApplication) getApplicationContext()).getOkHttpClient(); 78 | mHandler = new Handler(); 79 | initView(); 80 | initListener(); 81 | //在 Activity 中显示进度条的同时,也在 Fragment 中显示对应 url 的进度条,为了展示此框架的多端同步更新某一个进度信息 82 | getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, 83 | AdvanceFragment.newInstance(mNewImageUrl, mNewDownloadUrl, mNewUploadUrl)).commit(); 84 | } 85 | 86 | 87 | private void initView() { 88 | setContentView(R.layout.activity_advance); 89 | mImageView = findViewById(R.id.imageView); 90 | mGlideProgress = findViewById(R.id.glide_progress); 91 | mDownloadProgress = findViewById(R.id.download_progress); 92 | mUploadProgress = findViewById(R.id.upload_progress); 93 | mGlideProgressText = findViewById(R.id.glide_progress_text); 94 | mDownloadProgressText = findViewById(R.id.download_progress_text); 95 | mUploadProgressText = findViewById(R.id.upload_progress_text); 96 | findViewById(R.id.glide_start).setOnClickListener(this); 97 | findViewById(R.id.download_start).setOnClickListener(this); 98 | findViewById(R.id.upload_start).setOnClickListener(this); 99 | } 100 | 101 | private void initListener() { 102 | //图片和下载 (上传也同样支持) 使用同一个 url 地址,是为了展示高级功能 103 | //高级功能是为了应对当需要使用同一个 url 地址根据 Post 请求参数的不同而下载或上传不同资源的情况 104 | //"http://jessyancoding.github.io/images/RxCache.png" 会重定向到 "http://jessyan.me/images/RxCache.png" 105 | //所以也展示了高级功能同时完美兼容重定向 106 | //这里需要注意的是虽然使用的是新的 url 地址进行上传或下载,但实际请求服务器的 url 地址,还是原始的 url 地址 107 | //在监听器内部已经进行了处理,所以高级功能并不会影响服务器的请求 108 | 109 | //Glide 加载监听 110 | mNewImageUrl = ProgressManager 111 | .getInstance() 112 | .addDiffResponseListenerOnSameUrl("http://jessyancoding.github.io/images/RxCache.png", getGlideListener()); 113 | 114 | 115 | //Okhttp/Retofit 下载监听 116 | mNewDownloadUrl = ProgressManager 117 | .getInstance() 118 | .addDiffResponseListenerOnSameUrl("http://jessyancoding.github.io/images/RxCache.png", getDownloadListener()); 119 | 120 | 121 | //Okhttp/Retofit 上传监听 122 | mNewUploadUrl = ProgressManager 123 | .getInstance() 124 | .addDiffRequestListenerOnSameUrl("http://upload.qiniu.com/", "test", getUploadListener()); 125 | } 126 | 127 | 128 | @NonNull 129 | private ProgressListener getGlideListener() { 130 | return new ProgressListener() { 131 | @Override 132 | public void onProgress(ProgressInfo progressInfo) { 133 | int progress = progressInfo.getPercent(); 134 | mGlideProgress.setProgress(progress); 135 | mGlideProgressText.setText(progress + "%"); 136 | Log.d(TAG, "--Glide-- " + progress + " % " + progressInfo.getSpeed() + " byte/s " + progressInfo.toString()); 137 | if (progressInfo.isFinish()) { 138 | //说明已经加载完成 139 | Log.d(TAG, "--Glide-- finish"); 140 | } 141 | } 142 | 143 | @Override 144 | public void onError(long id, Exception e) { 145 | mHandler.post(new Runnable() { 146 | @Override 147 | public void run() { 148 | mGlideProgress.setProgress(0); 149 | mGlideProgressText.setText("error"); 150 | } 151 | }); 152 | } 153 | }; 154 | } 155 | 156 | @NonNull 157 | private ProgressListener getUploadListener() { 158 | return new ProgressListener() { 159 | @Override 160 | public void onProgress(ProgressInfo progressInfo) { 161 | // 如果你不屏蔽用户重复点击上传或下载按钮,就可能存在同一个 Url 地址,上一次的上传或下载操作都还没结束, 162 | // 又开始了新的上传或下载操作,那现在就需要用到 id(请求开始时的时间) 来区分正在执行的进度信息 163 | // 这里我就取最新的上传进度用来展示,顺便展示下 id 的用法 164 | 165 | if (mLastUploadingingInfo == null) { 166 | mLastUploadingingInfo = progressInfo; 167 | } 168 | 169 | //因为是以请求开始时的时间作为 Id ,所以值越大,说明该请求越新 170 | if (progressInfo.getId() < mLastUploadingingInfo.getId()) { 171 | return; 172 | } else if (progressInfo.getId() > mLastUploadingingInfo.getId()) { 173 | mLastUploadingingInfo = progressInfo; 174 | } 175 | 176 | int progress = mLastUploadingingInfo.getPercent(); 177 | mUploadProgress.setProgress(progress); 178 | mUploadProgressText.setText(progress + "%"); 179 | Log.d(TAG, "--Upload-- " + progress + " % " + mLastUploadingingInfo.getSpeed() + " byte/s " + mLastUploadingingInfo.toString()); 180 | if (mLastUploadingingInfo.isFinish()) { 181 | //说明已经上传完成 182 | Log.d(TAG, "--Upload-- finish"); 183 | } 184 | } 185 | 186 | @Override 187 | public void onError(long id, Exception e) { 188 | mHandler.post(new Runnable() { 189 | @Override 190 | public void run() { 191 | mUploadProgress.setProgress(0); 192 | mUploadProgressText.setText("error"); 193 | } 194 | }); 195 | } 196 | }; 197 | } 198 | 199 | @NonNull 200 | private ProgressListener getDownloadListener() { 201 | return new ProgressListener() { 202 | @Override 203 | public void onProgress(ProgressInfo progressInfo) { 204 | // 如果你不屏蔽用户重复点击上传或下载按钮,就可能存在同一个 Url 地址,上一次的上传或下载操作都还没结束, 205 | // 又开始了新的上传或下载操作,那现在就需要用到 id(请求开始时的时间) 来区分正在执行的进度信息 206 | // 这里我就取最新的下载进度用来展示,顺便展示下 id 的用法 207 | 208 | if (mLastDownloadingInfo == null) { 209 | mLastDownloadingInfo = progressInfo; 210 | } 211 | 212 | //因为是以请求开始时的时间作为 Id ,所以值越大,说明该请求越新 213 | if (progressInfo.getId() < mLastDownloadingInfo.getId()) { 214 | return; 215 | } else if (progressInfo.getId() > mLastDownloadingInfo.getId()) { 216 | mLastDownloadingInfo = progressInfo; 217 | } 218 | 219 | int progress = mLastDownloadingInfo.getPercent(); 220 | mDownloadProgress.setProgress(progress); 221 | mDownloadProgressText.setText(progress + "%"); 222 | Log.d(TAG, "--Download-- " + progress + " % " + mLastDownloadingInfo.getSpeed() + " byte/s " + mLastDownloadingInfo.toString()); 223 | if (mLastDownloadingInfo.isFinish()) { 224 | //说明已经下载完成 225 | Log.d(TAG, "--Download-- finish"); 226 | } 227 | } 228 | 229 | @Override 230 | public void onError(long id, Exception e) { 231 | mHandler.post(new Runnable() { 232 | @Override 233 | public void run() { 234 | mDownloadProgress.setProgress(0); 235 | mDownloadProgressText.setText("error"); 236 | } 237 | }); 238 | } 239 | }; 240 | } 241 | 242 | 243 | @Override 244 | public void onClick(View v) { 245 | switch (v.getId()) { 246 | case R.id.glide_start: 247 | glideStart(); 248 | break; 249 | case R.id.download_start: 250 | downloadStart(); 251 | break; 252 | case R.id.upload_start: 253 | uploadStart(); 254 | break; 255 | } 256 | } 257 | 258 | /** 259 | * 点击开始上传资源,为了演示,就不做重复点击的处理,即允许用户在还有进度没完成的情况下,使用同一个 url 开始新的上传 260 | */ 261 | private void uploadStart() { 262 | new Thread(new Runnable() { 263 | @Override 264 | public void run() { 265 | try { 266 | //为了方便就不动态申请权限了,直接将文件放到CacheDir()中 267 | File file = new File(getCacheDir(), "a.java"); 268 | //读取Assets里面的数据,作为上传源数据 269 | writeToFile(getAssets().open("a.java"), file); 270 | 271 | Request request = new Request.Builder() 272 | .url(mNewUploadUrl) 273 | .post(RequestBody.create(MediaType.parse("multipart/form-data"), file)) 274 | .build(); 275 | 276 | Response response = mOkHttpClient.newCall(request).execute(); 277 | response.body(); 278 | } catch (IOException e) { 279 | e.printStackTrace(); 280 | //当外部发生错误时,使用此方法可以通知所有监听器的 onError 方法 281 | ProgressManager.getInstance().notifyOnErorr(mNewUploadUrl, e); 282 | } 283 | } 284 | }).start(); 285 | } 286 | 287 | /** 288 | * 点击开始下载资源,为了演示,就不做重复点击的处理,即允许用户在还有进度没完成的情况下,使用同一个 url 开始新的下载 289 | */ 290 | private void downloadStart() { 291 | new Thread(new Runnable() { 292 | @Override 293 | public void run() { 294 | try { 295 | Request request = new Request.Builder() 296 | .url(mNewDownloadUrl) 297 | .build(); 298 | 299 | Response response = mOkHttpClient.newCall(request).execute(); 300 | 301 | InputStream is = response.body().byteStream(); 302 | //为了方便就不动态申请权限了,直接将文件放到CacheDir()中 303 | File file = new File(getCacheDir(), "download"); 304 | FileOutputStream fos = new FileOutputStream(file); 305 | BufferedInputStream bis = new BufferedInputStream(is); 306 | byte[] buffer = new byte[1024]; 307 | int len; 308 | while ((len = bis.read(buffer)) != -1) { 309 | fos.write(buffer, 0, len); 310 | } 311 | fos.flush(); 312 | fos.close(); 313 | bis.close(); 314 | is.close(); 315 | 316 | 317 | } catch (IOException e) { 318 | e.printStackTrace(); 319 | //当外部发生错误时,使用此方法可以通知所有监听器的 onError 方法 320 | ProgressManager.getInstance().notifyOnErorr(mNewDownloadUrl, e); 321 | } 322 | } 323 | }).start(); 324 | } 325 | 326 | /** 327 | * 点击开始 Glide 加载图片,为了演示,就不做重复点击的处理,但是 Glide 自己对重复加载做了处理 328 | * 即重复加载同一个 Url 时,停止还在请求当中的进度,再开启新的加载 329 | */ 330 | private void glideStart() { 331 | GlideApp.with(this) 332 | .load(mNewImageUrl) 333 | .centerCrop() 334 | .placeholder(R.color.colorPrimary) 335 | .diskCacheStrategy(DiskCacheStrategy.NONE) 336 | .into(mImageView); 337 | } 338 | 339 | @Override 340 | protected void onDestroy() { 341 | super.onDestroy(); 342 | //记得释放引用 343 | mNewImageUrl = null; 344 | mNewDownloadUrl = null; 345 | mNewUploadUrl = null; 346 | } 347 | 348 | public static File writeToFile(InputStream in, File file) throws IOException { 349 | FileOutputStream out = new FileOutputStream(file); 350 | byte[] buf = new byte[1024]; 351 | int num = 0; 352 | while ((num = in.read(buf)) != -1) { 353 | out.write(buf, 0, buf.length); 354 | } 355 | out.close(); 356 | return file; 357 | } 358 | } 359 | -------------------------------------------------------------------------------- /app/src/main/java/me/jessyan/progressmanager/demo/AdvanceFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package me.jessyan.progressmanager.demo; 17 | 18 | import android.os.Bundle; 19 | import android.os.Handler; 20 | import android.support.annotation.NonNull; 21 | import android.support.annotation.Nullable; 22 | import android.support.v4.app.Fragment; 23 | import android.util.Log; 24 | import android.view.LayoutInflater; 25 | import android.view.View; 26 | import android.view.ViewGroup; 27 | import android.widget.ProgressBar; 28 | import android.widget.TextView; 29 | 30 | import java.util.ArrayList; 31 | import java.util.Arrays; 32 | 33 | import me.jessyan.progressmanager.ProgressListener; 34 | import me.jessyan.progressmanager.ProgressManager; 35 | import me.jessyan.progressmanager.body.ProgressInfo; 36 | 37 | /** 38 | * ================================================ 39 | * Created by JessYan on 08/06/2017 12:59 40 | * Contact me 41 | * Follow me 42 | * ================================================ 43 | */ 44 | public class AdvanceFragment extends Fragment { 45 | private static final String TAG = "AdvanceFragment"; 46 | 47 | private ProgressBar mGlideProgress; 48 | private ProgressBar mDownloadProgress; 49 | private ProgressBar mUploadProgress; 50 | private TextView mGlideProgressText; 51 | private TextView mDownloadProgressText; 52 | private TextView mUploadProgressText; 53 | private View mRootView; 54 | 55 | private ProgressInfo mLastDownloadingInfo; 56 | private ProgressInfo mLastUploadingingInfo; 57 | private Handler mHandler; 58 | private static final String URL_BUNDLE_KEY = "url_bundle_key"; 59 | 60 | public static AdvanceFragment newInstance(String imageUrl, String downloadUrl, String uploadUrl) { 61 | AdvanceFragment fragment = new AdvanceFragment(); 62 | Bundle bundle = new Bundle(); 63 | ArrayList list = new ArrayList<>(Arrays.asList(imageUrl, downloadUrl, uploadUrl)); 64 | bundle.putStringArrayList(URL_BUNDLE_KEY, list); 65 | fragment.setArguments(bundle); 66 | return fragment; 67 | } 68 | 69 | @Nullable 70 | @Override 71 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 72 | mRootView = inflater.inflate(R.layout.fragment_main, container, false); 73 | return mRootView; 74 | } 75 | 76 | 77 | @Override 78 | public void onActivityCreated(@Nullable Bundle savedInstanceState) { 79 | super.onActivityCreated(savedInstanceState); 80 | mHandler = new Handler(); 81 | initView(); 82 | initData(); 83 | } 84 | 85 | 86 | private void initView() { 87 | mGlideProgress = mRootView.findViewById(R.id.glide_progress); 88 | mDownloadProgress = mRootView.findViewById(R.id.download_progress); 89 | mUploadProgress = mRootView.findViewById(R.id.upload_progress); 90 | mGlideProgressText = mRootView.findViewById(R.id.glide_progress_text); 91 | mDownloadProgressText = mRootView.findViewById(R.id.download_progress_text); 92 | mUploadProgressText = mRootView.findViewById(R.id.upload_progress_text); 93 | } 94 | 95 | private void initData() { 96 | Bundle arguments = getArguments(); 97 | ArrayList list = arguments.getStringArrayList(URL_BUNDLE_KEY); 98 | if (list == null || list.isEmpty()) 99 | return; 100 | //Glide 加载监听 101 | ProgressManager.getInstance().addResponseListener(list.get(0), getGlideListener()); 102 | 103 | //Okhttp/Retofit 下载监听 104 | ProgressManager.getInstance().addResponseListener(list.get(1), getDownloadListener()); 105 | 106 | //Okhttp/Retofit 上传监听 107 | ProgressManager.getInstance().addRequestListener(list.get(2), getUploadListener()); 108 | list.clear(); //清理 list 的引用 109 | } 110 | 111 | 112 | @NonNull 113 | private ProgressListener getUploadListener() { 114 | return new ProgressListener() { 115 | @Override 116 | public void onProgress(ProgressInfo progressInfo) { 117 | // 如果你不屏蔽用户重复点击上传或下载按钮,就可能存在同一个 Url 地址,上一次的上传或下载操作都还没结束, 118 | // 又开始了新的上传或下载操作,那现在就需要用到 id(请求开始时的时间) 来区分正在执行的进度信息 119 | // 这里我就取最新的上传进度用来展示,顺便展示下 id 的用法 120 | 121 | if (mLastUploadingingInfo == null) { 122 | mLastUploadingingInfo = progressInfo; 123 | } 124 | 125 | //因为是以请求开始时的时间作为 Id ,所以值越大,说明该请求越新 126 | if (progressInfo.getId() < mLastUploadingingInfo.getId()) { 127 | return; 128 | } else if (progressInfo.getId() > mLastUploadingingInfo.getId()) { 129 | mLastUploadingingInfo = progressInfo; 130 | } 131 | 132 | 133 | int progress = mLastUploadingingInfo.getPercent(); 134 | mUploadProgress.setProgress(progress); 135 | mUploadProgressText.setText(progress + "%"); 136 | Log.d(TAG, "--Upload-- " + progress + " %"); 137 | } 138 | 139 | @Override 140 | public void onError(long id, Exception e) { 141 | mHandler.post(new Runnable() { 142 | @Override 143 | public void run() { 144 | mUploadProgress.setProgress(0); 145 | mUploadProgressText.setText("error"); 146 | } 147 | }); 148 | } 149 | }; 150 | } 151 | 152 | @NonNull 153 | private ProgressListener getDownloadListener() { 154 | return new ProgressListener() { 155 | @Override 156 | public void onProgress(ProgressInfo progressInfo) { 157 | // 如果你不屏蔽用户重复点击上传或下载按钮,就可能存在同一个 Url 地址,上一次的上传或下载操作都还没结束, 158 | // 又开始了新的上传或下载操作,那现在就需要用到 id(请求开始时的时间) 来区分正在执行的进度信息 159 | // 这里我就取最新的下载进度用来展示,顺便展示下 id 的用法 160 | 161 | if (mLastDownloadingInfo == null) { 162 | mLastDownloadingInfo = progressInfo; 163 | } 164 | 165 | //因为是以请求开始时的时间作为 Id ,所以值越大,说明该请求越新 166 | if (progressInfo.getId() < mLastDownloadingInfo.getId()) { 167 | return; 168 | } else if (progressInfo.getId() > mLastDownloadingInfo.getId()) { 169 | mLastDownloadingInfo = progressInfo; 170 | } 171 | 172 | int progress = mLastDownloadingInfo.getPercent(); 173 | mDownloadProgress.setProgress(progress); 174 | mDownloadProgressText.setText(progress + "%"); 175 | Log.d(TAG, "--Download-- " + progress + " %"); 176 | } 177 | 178 | @Override 179 | public void onError(long id, Exception e) { 180 | mHandler.post(new Runnable() { 181 | @Override 182 | public void run() { 183 | mDownloadProgress.setProgress(0); 184 | mDownloadProgressText.setText("error"); 185 | } 186 | }); 187 | } 188 | }; 189 | } 190 | 191 | @NonNull 192 | private ProgressListener getGlideListener() { 193 | return new ProgressListener() { 194 | @Override 195 | public void onProgress(ProgressInfo progressInfo) { 196 | int progress = progressInfo.getPercent(); 197 | mGlideProgress.setProgress(progress); 198 | mGlideProgressText.setText(progress + "%"); 199 | Log.d(TAG, "--Glide-- " + progress + " %"); 200 | } 201 | 202 | @Override 203 | public void onError(long id, Exception e) { 204 | mHandler.post(new Runnable() { 205 | @Override 206 | public void run() { 207 | mGlideProgress.setProgress(0); 208 | mGlideProgressText.setText("error"); 209 | } 210 | }); 211 | } 212 | }; 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /app/src/main/java/me/jessyan/progressmanager/demo/BaseApplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package me.jessyan.progressmanager.demo; 17 | 18 | import android.app.Application; 19 | 20 | import me.jessyan.progressmanager.ProgressManager; 21 | import okhttp3.OkHttpClient; 22 | 23 | /** 24 | * ================================================ 25 | * Created by JessYan on 06/06/2017 16:29 26 | * Contact me 27 | * Follow me 28 | * ================================================ 29 | */ 30 | public class BaseApplication extends Application { 31 | 32 | //这里我就不写管理类了,捡个懒,直接在 Application 中管理单例 Okhttp 33 | private OkHttpClient mOkHttpClient; 34 | 35 | @Override 36 | public void onCreate() { 37 | super.onCreate(); 38 | this.mOkHttpClient = ProgressManager.getInstance().with(new OkHttpClient.Builder()) 39 | .build(); 40 | } 41 | 42 | 43 | public OkHttpClient getOkHttpClient() { 44 | return mOkHttpClient; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /app/src/main/java/me/jessyan/progressmanager/demo/GlideConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package me.jessyan.progressmanager.demo; 17 | 18 | import android.content.Context; 19 | 20 | import com.bumptech.glide.Glide; 21 | import com.bumptech.glide.GlideBuilder; 22 | import com.bumptech.glide.Registry; 23 | import com.bumptech.glide.annotation.GlideModule; 24 | import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader; 25 | import com.bumptech.glide.load.model.GlideUrl; 26 | import com.bumptech.glide.module.AppGlideModule; 27 | 28 | import java.io.InputStream; 29 | 30 | /** 31 | * ================================================ 32 | * Created by JessYan on 06/06/2017 16:41 33 | * Contact me 34 | * Follow me 35 | * ================================================ 36 | */ 37 | @GlideModule 38 | public class GlideConfiguration extends AppGlideModule { 39 | @Override 40 | public void applyOptions(Context context, GlideBuilder builder) { 41 | 42 | } 43 | 44 | @Override 45 | public void registerComponents(Context context, Glide glide, Registry registry) { 46 | BaseApplication application = (BaseApplication) context.getApplicationContext(); 47 | //Glide 底层默认使用 HttpConnection 进行网络请求,这里替换为 Okhttp 后才能使用本框架,进行 Glide 的加载进度监听 48 | registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(application.getOkHttpClient())); 49 | } 50 | 51 | @Override 52 | public boolean isManifestParsingEnabled() { 53 | return false; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /app/src/main/java/me/jessyan/progressmanager/demo/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package me.jessyan.progressmanager.demo; 17 | 18 | import android.content.Intent; 19 | import android.os.Bundle; 20 | import android.os.Handler; 21 | import android.support.annotation.NonNull; 22 | import android.support.v7.app.AppCompatActivity; 23 | import android.util.Log; 24 | import android.view.View; 25 | import android.widget.ImageView; 26 | import android.widget.ProgressBar; 27 | import android.widget.TextView; 28 | 29 | import com.bumptech.glide.load.engine.DiskCacheStrategy; 30 | 31 | import java.io.BufferedInputStream; 32 | import java.io.File; 33 | import java.io.FileOutputStream; 34 | import java.io.IOException; 35 | import java.io.InputStream; 36 | import java.util.WeakHashMap; 37 | 38 | import me.jessyan.progressmanager.ProgressListener; 39 | import me.jessyan.progressmanager.ProgressManager; 40 | import me.jessyan.progressmanager.body.ProgressInfo; 41 | import okhttp3.MediaType; 42 | import okhttp3.OkHttpClient; 43 | import okhttp3.Request; 44 | import okhttp3.RequestBody; 45 | import okhttp3.Response; 46 | import okhttp3.ResponseBody; 47 | 48 | /** 49 | * ================================================ 50 | * 这里展示框架的基本功能, 高级功能请看 {@link AdvanceActivity} 51 | * 代码虽然多,但核心方法就在 {@link BaseApplication#onCreate()} 和 {@link #initListener()} 这两处 52 | * 其他代码都是在做请求和下载以及 UI 展示, 和框架没有任何关系, 可以作为参考, 但这些代码每个项目都不一样 53 | * 比如你喜欢用 Retrofit 的 {@code @Multipart} 进行资源的上传, 这些看个人的喜好进行修改 54 | *

55 | * 请注意 Demo 只展示了 Okhttp 的下载上传监听和 Glide 的加载监听 56 | * 但是 Retrofit 的下载和上传监听同样完美支持 57 | * 因为 Retrofit 底层默认使用的是 Okhttp 做网络请求, 所以只要您照着 {@link BaseApplication#onCreate()} 中的代码 58 | * 给 Okhttp 配置了 {@link okhttp3.Interceptor}, 并且使用 {@link ProgressManager#addResponseListener(String, ProgressListener)} 59 | * 或 {@link ProgressManager#addResponseListener(String, ProgressListener)} 给对应的 {@code url} 添加了监听器 60 | *

61 | * 当做了以上两步操作后, 不管您是使用 Retrofit, Okhttp 还是 Glide, 以及请求或下载的方式, 代码的结构层次, 这些东西不管如何变化, 都不会对监听效果有任何影响 62 | * 只要这个 {@code url} 存在上传 (请求时有 {@link RequestBody}) 或下载 (服务器有返回 {@link ResponseBody}) 的动作时, 监听器就一定会被调用 63 | *

64 | * Created by JessYan on 08/06/2017 12:59 65 | * Contact me 66 | * Follow me 67 | * ================================================ 68 | */ 69 | public class MainActivity extends AppCompatActivity implements View.OnClickListener { 70 | private static final String TAG = "MainActivity"; 71 | /** 72 | * 全局持有 url 是为了使用 {@link WeakHashMap} 的特性,在 {@link ProgressManager} 中顶部有介绍 73 | * 使用 String mUrl = new String("url");, 而不是 String mUrl = "url"; 74 | * 为什么这样做? 因为如果直接使用 String mUrl = "url", 这个 url 字符串会被加入全局字符串常量池, 池中的字符串将不会被回收 75 | * 既然 {@code key} 没被回收, 那 {@link WeakHashMap} 中的值也不会被移除 76 | * 在 {@link #onDestroy()} 中一定记得释放被引用的 url (将 url 设为 null), 这样框架就能在 java 虚拟机 GC 时释放对应的监听器 77 | */ 78 | public String mImageUrl = new String("https://raw.githubusercontent.com/JessYanCoding/MVPArmsTemplate/master/art/step.png"); 79 | public String mDownloadUrl = new String("https://raw.githubusercontent.com/JessYanCoding/MVPArmsTemplate/master/art/MVPArms.gif"); 80 | public String mUploadUrl = new String("http://upload.qiniu.com/"); 81 | 82 | private ImageView mImageView; 83 | private OkHttpClient mOkHttpClient; 84 | private ProgressBar mGlideProgress; 85 | private ProgressBar mDownloadProgress; 86 | private ProgressBar mUploadProgress; 87 | private TextView mGlideProgressText; 88 | private TextView mDownloadProgressText; 89 | private TextView mUploadProgressText; 90 | 91 | private ProgressInfo mLastDownloadingInfo; 92 | private ProgressInfo mLastUploadingingInfo; 93 | private Handler mHandler; 94 | 95 | 96 | @Override 97 | protected void onCreate(Bundle savedInstanceState) { 98 | super.onCreate(savedInstanceState); 99 | mOkHttpClient = ((BaseApplication) getApplicationContext()).getOkHttpClient(); 100 | mHandler = new Handler(); 101 | initView(); 102 | initListener(); 103 | //在 Activity 中显示进度条的同时,也在 Fragment 中显示对应 url 的进度条,为了展示此框架的多端同步更新某一个进度信息 104 | getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, 105 | MainFragment.newInstance(mImageUrl, mDownloadUrl, mUploadUrl)).commit(); 106 | } 107 | 108 | 109 | private void initView() { 110 | setContentView(R.layout.activity_main); 111 | mImageView = findViewById(R.id.imageView); 112 | mGlideProgress = findViewById(R.id.glide_progress); 113 | mDownloadProgress = findViewById(R.id.download_progress); 114 | mUploadProgress = findViewById(R.id.upload_progress); 115 | mGlideProgressText = findViewById(R.id.glide_progress_text); 116 | mDownloadProgressText = findViewById(R.id.download_progress_text); 117 | mUploadProgressText = findViewById(R.id.upload_progress_text); 118 | findViewById(R.id.glide_start).setOnClickListener(this); 119 | findViewById(R.id.download_start).setOnClickListener(this); 120 | findViewById(R.id.upload_start).setOnClickListener(this); 121 | findViewById(R.id.advance).setOnClickListener(this); 122 | } 123 | 124 | private void initListener() { 125 | //Glide 加载监听 126 | ProgressManager.getInstance().addResponseListener(mImageUrl, getGlideListener()); 127 | 128 | 129 | //Okhttp/Retofit 下载监听 130 | ProgressManager.getInstance().addResponseListener(mDownloadUrl, getDownloadListener()); 131 | 132 | 133 | //Okhttp/Retofit 上传监听 134 | ProgressManager.getInstance().addRequestListener(mUploadUrl, getUploadListener()); 135 | } 136 | 137 | 138 | @NonNull 139 | private ProgressListener getGlideListener() { 140 | return new ProgressListener() { 141 | @Override 142 | public void onProgress(ProgressInfo progressInfo) { 143 | int progress = progressInfo.getPercent(); 144 | mGlideProgress.setProgress(progress); 145 | mGlideProgressText.setText(progress + "%"); 146 | Log.d(TAG, "--Glide-- " + progress + " % " + progressInfo.getSpeed() + " byte/s " + progressInfo.toString()); 147 | if (progressInfo.isFinish()) { 148 | //说明已经加载完成 149 | Log.d(TAG, "--Glide-- finish"); 150 | } 151 | } 152 | 153 | @Override 154 | public void onError(long id, Exception e) { 155 | mHandler.post(new Runnable() { 156 | @Override 157 | public void run() { 158 | mGlideProgress.setProgress(0); 159 | mGlideProgressText.setText("error"); 160 | } 161 | }); 162 | } 163 | }; 164 | } 165 | 166 | @NonNull 167 | private ProgressListener getUploadListener() { 168 | return new ProgressListener() { 169 | @Override 170 | public void onProgress(ProgressInfo progressInfo) { 171 | // 如果你不屏蔽用户重复点击上传或下载按钮,就可能存在同一个 Url 地址,上一次的上传或下载操作都还没结束, 172 | // 又开始了新的上传或下载操作,那现在就需要用到 id(请求开始时的时间) 来区分正在执行的进度信息 173 | // 这里我就取最新的上传进度用来展示,顺便展示下 id 的用法 174 | 175 | if (mLastUploadingingInfo == null) { 176 | mLastUploadingingInfo = progressInfo; 177 | } 178 | 179 | //因为是以请求开始时的时间作为 Id ,所以值越大,说明该请求越新 180 | if (progressInfo.getId() < mLastUploadingingInfo.getId()) { 181 | return; 182 | } else if (progressInfo.getId() > mLastUploadingingInfo.getId()) { 183 | mLastUploadingingInfo = progressInfo; 184 | } 185 | 186 | int progress = mLastUploadingingInfo.getPercent(); 187 | mUploadProgress.setProgress(progress); 188 | mUploadProgressText.setText(progress + "%"); 189 | Log.d(TAG, "--Upload-- " + progress + " % " + mLastUploadingingInfo.getSpeed() + " byte/s " + mLastUploadingingInfo.toString()); 190 | if (mLastUploadingingInfo.isFinish()) { 191 | //说明已经上传完成 192 | Log.d(TAG, "--Upload-- finish"); 193 | } 194 | } 195 | 196 | @Override 197 | public void onError(long id, Exception e) { 198 | mHandler.post(new Runnable() { 199 | @Override 200 | public void run() { 201 | mUploadProgress.setProgress(0); 202 | mUploadProgressText.setText("error"); 203 | } 204 | }); 205 | } 206 | }; 207 | } 208 | 209 | @NonNull 210 | private ProgressListener getDownloadListener() { 211 | return new ProgressListener() { 212 | @Override 213 | public void onProgress(ProgressInfo progressInfo) { 214 | // 如果你不屏蔽用户重复点击上传或下载按钮,就可能存在同一个 Url 地址,上一次的上传或下载操作都还没结束, 215 | // 又开始了新的上传或下载操作,那现在就需要用到 id(请求开始时的时间) 来区分正在执行的进度信息 216 | // 这里我就取最新的下载进度用来展示,顺便展示下 id 的用法 217 | 218 | if (mLastDownloadingInfo == null) { 219 | mLastDownloadingInfo = progressInfo; 220 | } 221 | 222 | //因为是以请求开始时的时间作为 Id ,所以值越大,说明该请求越新 223 | if (progressInfo.getId() < mLastDownloadingInfo.getId()) { 224 | return; 225 | } else if (progressInfo.getId() > mLastDownloadingInfo.getId()) { 226 | mLastDownloadingInfo = progressInfo; 227 | } 228 | 229 | int progress = mLastDownloadingInfo.getPercent(); 230 | mDownloadProgress.setProgress(progress); 231 | mDownloadProgressText.setText(progress + "%"); 232 | Log.d(TAG, "--Download-- " + progress + " % " + mLastDownloadingInfo.getSpeed() + " byte/s " + mLastDownloadingInfo.toString()); 233 | if (mLastDownloadingInfo.isFinish()) { 234 | //说明已经下载完成 235 | Log.d(TAG, "--Download-- finish"); 236 | } 237 | } 238 | 239 | @Override 240 | public void onError(long id, Exception e) { 241 | mHandler.post(new Runnable() { 242 | @Override 243 | public void run() { 244 | mDownloadProgress.setProgress(0); 245 | mDownloadProgressText.setText("error"); 246 | } 247 | }); 248 | } 249 | }; 250 | } 251 | 252 | 253 | @Override 254 | public void onClick(View v) { 255 | switch (v.getId()) { 256 | case R.id.glide_start: 257 | glideStart(); 258 | break; 259 | case R.id.download_start: 260 | downloadStart(); 261 | break; 262 | case R.id.upload_start: 263 | uploadStart(); 264 | break; 265 | case R.id.advance: 266 | startActivity(new Intent(getApplicationContext(), AdvanceActivity.class)); 267 | break; 268 | } 269 | } 270 | 271 | /** 272 | * 点击开始上传资源,为了演示,就不做重复点击的处理,即允许用户在还有进度没完成的情况下,使用同一个 url 开始新的上传 273 | */ 274 | private void uploadStart() { 275 | new Thread(new Runnable() { 276 | @Override 277 | public void run() { 278 | try { 279 | //为了方便就不动态申请权限了,直接将文件放到CacheDir()中 280 | File file = new File(getCacheDir(), "a.java"); 281 | //读取Assets里面的数据,作为上传源数据 282 | writeToFile(getAssets().open("a.java"), file); 283 | 284 | Request request = new Request.Builder() 285 | .url(mUploadUrl) 286 | .post(RequestBody.create(MediaType.parse("multipart/form-data"), file)) 287 | .build(); 288 | 289 | Response response = mOkHttpClient.newCall(request).execute(); 290 | response.body(); 291 | } catch (IOException e) { 292 | e.printStackTrace(); 293 | //当外部发生错误时,使用此方法可以通知所有监听器的 onError 方法 294 | ProgressManager.getInstance().notifyOnErorr(mUploadUrl, e); 295 | } 296 | } 297 | }).start(); 298 | } 299 | 300 | /** 301 | * 点击开始下载资源,为了演示,就不做重复点击的处理,即允许用户在还有进度没完成的情况下,使用同一个 url 开始新的下载 302 | */ 303 | private void downloadStart() { 304 | new Thread(new Runnable() { 305 | @Override 306 | public void run() { 307 | try { 308 | Request request = new Request.Builder() 309 | .url(mDownloadUrl) 310 | .build(); 311 | 312 | Response response = mOkHttpClient.newCall(request).execute(); 313 | 314 | InputStream is = response.body().byteStream(); 315 | //为了方便就不动态申请权限了,直接将文件放到CacheDir()中 316 | File file = new File(getCacheDir(), "download"); 317 | FileOutputStream fos = new FileOutputStream(file); 318 | BufferedInputStream bis = new BufferedInputStream(is); 319 | byte[] buffer = new byte[1024]; 320 | int len; 321 | while ((len = bis.read(buffer)) != -1) { 322 | fos.write(buffer, 0, len); 323 | } 324 | fos.flush(); 325 | fos.close(); 326 | bis.close(); 327 | is.close(); 328 | 329 | 330 | } catch (IOException e) { 331 | e.printStackTrace(); 332 | //当外部发生错误时,使用此方法可以通知所有监听器的 onError 方法 333 | ProgressManager.getInstance().notifyOnErorr(mDownloadUrl, e); 334 | } 335 | } 336 | }).start(); 337 | } 338 | 339 | /** 340 | * 点击开始 Glide 加载图片,为了演示,就不做重复点击的处理,但是 Glide 自己对重复加载做了处理 341 | * 即重复加载同一个 Url 时,停止还在请求当中的进度,再开启新的加载 342 | */ 343 | private void glideStart() { 344 | GlideApp.with(this) 345 | .load(mImageUrl) 346 | .centerCrop() 347 | .placeholder(R.color.colorPrimary) 348 | .diskCacheStrategy(DiskCacheStrategy.NONE) 349 | .into(mImageView); 350 | } 351 | 352 | @Override 353 | protected void onDestroy() { 354 | super.onDestroy(); 355 | //记得释放引用 356 | mImageUrl = null; 357 | mDownloadUrl = null; 358 | mUploadUrl = null; 359 | } 360 | 361 | public static File writeToFile(InputStream in, File file) throws IOException { 362 | FileOutputStream out = new FileOutputStream(file); 363 | byte[] buf = new byte[1024]; 364 | int num = 0; 365 | while ((num = in.read(buf)) != -1) { 366 | out.write(buf, 0, buf.length); 367 | } 368 | out.close(); 369 | return file; 370 | } 371 | } 372 | -------------------------------------------------------------------------------- /app/src/main/java/me/jessyan/progressmanager/demo/MainFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package me.jessyan.progressmanager.demo; 17 | 18 | import android.os.Bundle; 19 | import android.os.Handler; 20 | import android.support.annotation.NonNull; 21 | import android.support.annotation.Nullable; 22 | import android.support.v4.app.Fragment; 23 | import android.util.Log; 24 | import android.view.LayoutInflater; 25 | import android.view.View; 26 | import android.view.ViewGroup; 27 | import android.widget.ProgressBar; 28 | import android.widget.TextView; 29 | 30 | import java.util.ArrayList; 31 | import java.util.Arrays; 32 | 33 | import me.jessyan.progressmanager.ProgressListener; 34 | import me.jessyan.progressmanager.ProgressManager; 35 | import me.jessyan.progressmanager.body.ProgressInfo; 36 | 37 | /** 38 | * ================================================ 39 | * Created by JessYan on 08/06/2017 12:59 40 | * Contact me 41 | * Follow me 42 | * ================================================ 43 | */ 44 | public class MainFragment extends Fragment { 45 | private static final String TAG = "MainFragment"; 46 | 47 | private ProgressBar mGlideProgress; 48 | private ProgressBar mDownloadProgress; 49 | private ProgressBar mUploadProgress; 50 | private TextView mGlideProgressText; 51 | private TextView mDownloadProgressText; 52 | private TextView mUploadProgressText; 53 | private View mRootView; 54 | 55 | private ProgressInfo mLastDownloadingInfo; 56 | private ProgressInfo mLastUploadingingInfo; 57 | private Handler mHandler; 58 | private static final String URL_BUNDLE_KEY = "url_bundle_key"; 59 | 60 | public static MainFragment newInstance(String imageUrl, String downloadUrl, String uploadUrl) { 61 | MainFragment fragment = new MainFragment(); 62 | Bundle bundle = new Bundle(); 63 | ArrayList list = new ArrayList<>(Arrays.asList(imageUrl, downloadUrl, uploadUrl)); 64 | bundle.putStringArrayList(URL_BUNDLE_KEY, list); 65 | fragment.setArguments(bundle); 66 | return fragment; 67 | } 68 | 69 | @Nullable 70 | @Override 71 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 72 | mRootView = inflater.inflate(R.layout.fragment_main, container, false); 73 | return mRootView; 74 | } 75 | 76 | 77 | @Override 78 | public void onActivityCreated(@Nullable Bundle savedInstanceState) { 79 | super.onActivityCreated(savedInstanceState); 80 | mHandler = new Handler(); 81 | initView(); 82 | initData(); 83 | } 84 | 85 | 86 | private void initView() { 87 | mGlideProgress = mRootView.findViewById(R.id.glide_progress); 88 | mDownloadProgress = mRootView.findViewById(R.id.download_progress); 89 | mUploadProgress = mRootView.findViewById(R.id.upload_progress); 90 | mGlideProgressText = mRootView.findViewById(R.id.glide_progress_text); 91 | mDownloadProgressText = mRootView.findViewById(R.id.download_progress_text); 92 | mUploadProgressText = mRootView.findViewById(R.id.upload_progress_text); 93 | } 94 | 95 | private void initData() { 96 | Bundle arguments = getArguments(); 97 | ArrayList list = arguments.getStringArrayList(URL_BUNDLE_KEY); 98 | if (list == null || list.isEmpty()) 99 | return; 100 | //Glide 加载监听 101 | ProgressManager.getInstance().addResponseListener(list.get(0), getGlideListener()); 102 | 103 | //Okhttp/Retofit 下载监听 104 | ProgressManager.getInstance().addResponseListener(list.get(1), getDownloadListener()); 105 | 106 | //Okhttp/Retofit 上传监听 107 | ProgressManager.getInstance().addRequestListener(list.get(2), getUploadListener()); 108 | list.clear();//清理 list 里的引用 109 | } 110 | 111 | 112 | @NonNull 113 | private ProgressListener getUploadListener() { 114 | return new ProgressListener() { 115 | @Override 116 | public void onProgress(ProgressInfo progressInfo) { 117 | // 如果你不屏蔽用户重复点击上传或下载按钮,就可能存在同一个 Url 地址,上一次的上传或下载操作都还没结束, 118 | // 又开始了新的上传或下载操作,那现在就需要用到 id(请求开始时的时间) 来区分正在执行的进度信息 119 | // 这里我就取最新的上传进度用来展示,顺便展示下 id 的用法 120 | 121 | if (mLastUploadingingInfo == null) { 122 | mLastUploadingingInfo = progressInfo; 123 | } 124 | 125 | //因为是以请求开始时的时间作为 Id ,所以值越大,说明该请求越新 126 | if (progressInfo.getId() < mLastUploadingingInfo.getId()) { 127 | return; 128 | } else if (progressInfo.getId() > mLastUploadingingInfo.getId()) { 129 | mLastUploadingingInfo = progressInfo; 130 | } 131 | 132 | 133 | int progress = mLastUploadingingInfo.getPercent(); 134 | mUploadProgress.setProgress(progress); 135 | mUploadProgressText.setText(progress + "%"); 136 | Log.d(TAG, "--Upload-- " + progress + " %"); 137 | } 138 | 139 | @Override 140 | public void onError(long id, Exception e) { 141 | mHandler.post(new Runnable() { 142 | @Override 143 | public void run() { 144 | mUploadProgress.setProgress(0); 145 | mUploadProgressText.setText("error"); 146 | } 147 | }); 148 | } 149 | }; 150 | } 151 | 152 | @NonNull 153 | private ProgressListener getDownloadListener() { 154 | return new ProgressListener() { 155 | @Override 156 | public void onProgress(ProgressInfo progressInfo) { 157 | // 如果你不屏蔽用户重复点击上传或下载按钮,就可能存在同一个 Url 地址,上一次的上传或下载操作都还没结束, 158 | // 又开始了新的上传或下载操作,那现在就需要用到 id(请求开始时的时间) 来区分正在执行的进度信息 159 | // 这里我就取最新的下载进度用来展示,顺便展示下 id 的用法 160 | 161 | if (mLastDownloadingInfo == null) { 162 | mLastDownloadingInfo = progressInfo; 163 | } 164 | 165 | //因为是以请求开始时的时间作为 Id ,所以值越大,说明该请求越新 166 | if (progressInfo.getId() < mLastDownloadingInfo.getId()) { 167 | return; 168 | } else if (progressInfo.getId() > mLastDownloadingInfo.getId()) { 169 | mLastDownloadingInfo = progressInfo; 170 | } 171 | 172 | int progress = mLastDownloadingInfo.getPercent(); 173 | mDownloadProgress.setProgress(progress); 174 | mDownloadProgressText.setText(progress + "%"); 175 | Log.d(TAG, "--Download-- " + progress + " %"); 176 | } 177 | 178 | @Override 179 | public void onError(long id, Exception e) { 180 | mHandler.post(new Runnable() { 181 | @Override 182 | public void run() { 183 | mDownloadProgress.setProgress(0); 184 | mDownloadProgressText.setText("error"); 185 | } 186 | }); 187 | } 188 | }; 189 | } 190 | 191 | @NonNull 192 | private ProgressListener getGlideListener() { 193 | return new ProgressListener() { 194 | @Override 195 | public void onProgress(ProgressInfo progressInfo) { 196 | int progress = progressInfo.getPercent(); 197 | mGlideProgress.setProgress(progress); 198 | mGlideProgressText.setText(progress + "%"); 199 | Log.d(TAG, "--Glide-- " + progress + " %"); 200 | } 201 | 202 | @Override 203 | public void onError(long id, Exception e) { 204 | mHandler.post(new Runnable() { 205 | @Override 206 | public void run() { 207 | mGlideProgress.setProgress(0); 208 | mGlideProgressText.setText("error"); 209 | } 210 | }); 211 | } 212 | }; 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_advance.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 | 18 | 19 | 25 | 26 |