Repository: jeasonlzy/okhttp-OkGo
Branch: master
Commit: e34c2fa150db
Files: 276
Total size: 889.0 KB
Directory structure:
gitextract_01imco5q/
├── .gitignore
├── LICENSE
├── README.md
├── appkey.jks
├── build.gradle
├── demo/
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ └── main/
│ ├── AndroidManifest.xml
│ ├── assets/
│ │ └── srca.cer
│ ├── java/
│ │ └── com/
│ │ └── lzy/
│ │ └── demo/
│ │ ├── GApp.java
│ │ ├── MainActivity.java
│ │ ├── PayFragment.java
│ │ ├── WebActivity.java
│ │ ├── base/
│ │ │ ├── BaseActivity.java
│ │ │ ├── BaseDetailActivity.java
│ │ │ ├── BaseFragment.java
│ │ │ ├── BaseRecyclerAdapter.java
│ │ │ ├── BaseRxDetailActivity.java
│ │ │ ├── DividerItemDecoration.java
│ │ │ └── MainFragment.java
│ │ ├── callback/
│ │ │ ├── BitmapDialogCallback.java
│ │ │ ├── DialogCallback.java
│ │ │ ├── EncryptCallback.java
│ │ │ ├── JsonCallback.java
│ │ │ ├── JsonConvert.java
│ │ │ └── StringDialogCallback.java
│ │ ├── model/
│ │ │ ├── ApkModel.java
│ │ │ ├── GankModel.java
│ │ │ ├── GankResponse.java
│ │ │ ├── ItemModel.java
│ │ │ ├── LzyResponse.java
│ │ │ ├── ServerModel.java
│ │ │ └── SimpleResponse.java
│ │ ├── okdownload/
│ │ │ ├── DesActivity.java
│ │ │ ├── DownloadAdapter.java
│ │ │ ├── DownloadAllActivity.java
│ │ │ ├── DownloadFinishActivity.java
│ │ │ ├── DownloadListActivity.java
│ │ │ ├── DownloadingActivity.java
│ │ │ ├── LogDownloadListener.java
│ │ │ └── OkDownloadFragment.java
│ │ ├── okgo/
│ │ │ ├── BitmapRequestActivity.java
│ │ │ ├── CacheActivity.java
│ │ │ ├── CommonActivity.java
│ │ │ ├── CookieActivity.java
│ │ │ ├── FormUploadActivity.java
│ │ │ ├── HttpsActivity.java
│ │ │ ├── JsonActivity.java
│ │ │ ├── MethodActivity.java
│ │ │ ├── OkGoFragment.java
│ │ │ ├── RedirectActivity.java
│ │ │ ├── SimpleDownloadActivity.java
│ │ │ ├── SyncActivity.java
│ │ │ ├── TestActivity.java
│ │ │ └── UpActivity.java
│ │ ├── okrx2/
│ │ │ ├── OkRx2Fragment.java
│ │ │ ├── OkRxFragment.java
│ │ │ ├── RxBitmapActivity.java
│ │ │ ├── RxCacheActivity.java
│ │ │ ├── RxCommonActivity.java
│ │ │ ├── RxFileDownloadActivity.java
│ │ │ ├── RxFormUploadActivity.java
│ │ │ ├── RxRetrofitActivity.java
│ │ │ ├── RxUtils.java
│ │ │ └── ServerApi.java
│ │ ├── okupload/
│ │ │ ├── LogUploadListener.java
│ │ │ ├── OkUploadFragment.java
│ │ │ ├── UploadAdapter.java
│ │ │ ├── UploadAllActivity.java
│ │ │ ├── UploadFinishActivity.java
│ │ │ ├── UploadListActivity.java
│ │ │ └── UploadingActivity.java
│ │ ├── supercache/
│ │ │ ├── NewsAdapter.java
│ │ │ ├── NewsCallback.java
│ │ │ ├── NewsTabFragment.java
│ │ │ └── SuperCacheActivity.java
│ │ ├── ui/
│ │ │ ├── NumberProgressBar.java
│ │ │ ├── ProgressPieView.java
│ │ │ ├── SimpleViewBehavior.java
│ │ │ └── TranslateUpDownBehavior.java
│ │ └── utils/
│ │ ├── AnimHelper.java
│ │ ├── ApkUtils.java
│ │ ├── ColorUtils.java
│ │ ├── Convert.java
│ │ ├── GlideImageLoader.java
│ │ ├── MD5Utils.java
│ │ ├── PicassoImageLoader.java
│ │ └── Urls.java
│ └── res/
│ ├── drawable/
│ │ └── progress_bar_states.xml
│ ├── layout/
│ │ ├── activity_base.xml
│ │ ├── activity_bitmap_request.xml
│ │ ├── activity_cache.xml
│ │ ├── activity_cookie.xml
│ │ ├── activity_custom_request.xml
│ │ ├── activity_download_all.xml
│ │ ├── activity_download_details.xml
│ │ ├── activity_download_list.xml
│ │ ├── activity_file_download.xml
│ │ ├── activity_form_upload.xml
│ │ ├── activity_https.xml
│ │ ├── activity_main.xml
│ │ ├── activity_method.xml
│ │ ├── activity_recycler.xml
│ │ ├── activity_redirect.xml
│ │ ├── activity_rx_cache.xml
│ │ ├── activity_rx_common.xml
│ │ ├── activity_rx_file_download.xml
│ │ ├── activity_rx_form_upload.xml
│ │ ├── activity_rx_retrofit.xml
│ │ ├── activity_super_cache.xml
│ │ ├── activity_sync.xml
│ │ ├── activity_test.xml
│ │ ├── activity_up_text.xml
│ │ ├── activity_upload_list.xml
│ │ ├── activity_web.xml
│ │ ├── fragment_pay.xml
│ │ ├── include_data.xml
│ │ ├── item_download_list.xml
│ │ ├── item_download_manager.xml
│ │ ├── item_main_list.xml
│ │ ├── item_main_type.xml
│ │ ├── item_news.xml
│ │ ├── item_no_data.xml
│ │ ├── item_refresh.xml
│ │ └── item_upload_manager.xml
│ └── values/
│ ├── attrs.xml
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── jar/
│ ├── okgo-3.0.4.jar
│ ├── okhttp-3.8.1.jar
│ ├── okio-1.13.0.jar
│ ├── okrx-1.0.2.jar
│ ├── okrx2-2.0.2.jar
│ └── okserver-2.0.5.jar
├── okgo/
│ ├── .gitignore
│ ├── bintray.gradle
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ └── main/
│ ├── AndroidManifest.xml
│ └── java/
│ └── com/
│ └── lzy/
│ └── okgo/
│ ├── OkGo.java
│ ├── adapter/
│ │ ├── AdapterParam.java
│ │ ├── CacheCall.java
│ │ ├── Call.java
│ │ ├── CallAdapter.java
│ │ └── DefaultCallAdapter.java
│ ├── cache/
│ │ ├── CacheEntity.java
│ │ ├── CacheMode.java
│ │ └── policy/
│ │ ├── BaseCachePolicy.java
│ │ ├── CachePolicy.java
│ │ ├── DefaultCachePolicy.java
│ │ ├── FirstCacheRequestPolicy.java
│ │ ├── NoCachePolicy.java
│ │ ├── NoneCacheRequestPolicy.java
│ │ └── RequestFailedCachePolicy.java
│ ├── callback/
│ │ ├── AbsCallback.java
│ │ ├── BitmapCallback.java
│ │ ├── Callback.java
│ │ ├── FileCallback.java
│ │ └── StringCallback.java
│ ├── convert/
│ │ ├── BitmapConvert.java
│ │ ├── Converter.java
│ │ ├── FileConvert.java
│ │ └── StringConvert.java
│ ├── cookie/
│ │ ├── CookieJarImpl.java
│ │ ├── SerializableCookie.java
│ │ └── store/
│ │ ├── CookieStore.java
│ │ ├── DBCookieStore.java
│ │ ├── MemoryCookieStore.java
│ │ └── SPCookieStore.java
│ ├── db/
│ │ ├── BaseDao.java
│ │ ├── CacheManager.java
│ │ ├── ColumnEntity.java
│ │ ├── CookieManager.java
│ │ ├── DBHelper.java
│ │ ├── DBUtils.java
│ │ ├── DownloadManager.java
│ │ ├── TableEntity.java
│ │ └── UploadManager.java
│ ├── exception/
│ │ ├── CacheException.java
│ │ ├── HttpException.java
│ │ ├── OkGoException.java
│ │ └── StorageException.java
│ ├── https/
│ │ └── HttpsUtils.java
│ ├── interceptor/
│ │ └── HttpLoggingInterceptor.java
│ ├── model/
│ │ ├── HttpHeaders.java
│ │ ├── HttpMethod.java
│ │ ├── HttpParams.java
│ │ ├── Priority.java
│ │ ├── Progress.java
│ │ ├── Response.java
│ │ └── Result.java
│ ├── request/
│ │ ├── DeleteRequest.java
│ │ ├── GetRequest.java
│ │ ├── HeadRequest.java
│ │ ├── OptionsRequest.java
│ │ ├── PatchRequest.java
│ │ ├── PostRequest.java
│ │ ├── PutRequest.java
│ │ ├── TraceRequest.java
│ │ └── base/
│ │ ├── BodyRequest.java
│ │ ├── HasBody.java
│ │ ├── NoBodyRequest.java
│ │ ├── ProgressRequestBody.java
│ │ └── Request.java
│ └── utils/
│ ├── HeaderParser.java
│ ├── HttpUtils.java
│ ├── IOUtils.java
│ └── OkLogger.java
├── okrx/
│ ├── .gitignore
│ ├── bintray.gradle
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ └── main/
│ ├── AndroidManifest.xml
│ └── java/
│ └── com/
│ └── lzy/
│ └── okrx/
│ ├── adapter/
│ │ ├── AnalysisParams.java
│ │ ├── CompletableResponse.java
│ │ ├── ObservableBody.java
│ │ ├── ObservableResponse.java
│ │ ├── ObservableResult.java
│ │ ├── SingleBody.java
│ │ ├── SingleResponse.java
│ │ └── SingleResult.java
│ └── subscribe/
│ ├── BodyOnSubscribe.java
│ ├── CallArbiter.java
│ ├── CallEnqueueOnSubscribe.java
│ ├── CallExecuteOnSubscribe.java
│ └── ResultOnSubscribe.java
├── okrx2/
│ ├── .gitignore
│ ├── bintray.gradle
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ └── main/
│ ├── AndroidManifest.xml
│ └── java/
│ └── com/
│ └── lzy/
│ └── okrx2/
│ ├── adapter/
│ │ ├── AnalysisParams.java
│ │ ├── CompletableResponse.java
│ │ ├── FlowableBody.java
│ │ ├── FlowableResponse.java
│ │ ├── FlowableResult.java
│ │ ├── MaybeBody.java
│ │ ├── MaybeResponse.java
│ │ ├── MaybeResult.java
│ │ ├── ObservableBody.java
│ │ ├── ObservableResponse.java
│ │ ├── ObservableResult.java
│ │ ├── SingleBody.java
│ │ ├── SingleResponse.java
│ │ └── SingleResult.java
│ └── observable/
│ ├── BodyObservable.java
│ ├── CallEnqueueObservable.java
│ ├── CallExecuteObservable.java
│ └── ResultObservable.java
├── okserver/
│ ├── .gitignore
│ ├── bintray.gradle
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ └── main/
│ ├── AndroidManifest.xml
│ └── java/
│ └── com/
│ └── lzy/
│ └── okserver/
│ ├── OkDownload.java
│ ├── OkUpload.java
│ ├── ProgressListener.java
│ ├── download/
│ │ ├── DownloadListener.java
│ │ ├── DownloadTask.java
│ │ └── DownloadThreadPool.java
│ ├── task/
│ │ ├── PriorityBlockingQueue.java
│ │ ├── PriorityObject.java
│ │ ├── PriorityRunnable.java
│ │ └── XExecutor.java
│ └── upload/
│ ├── UploadListener.java
│ ├── UploadTask.java
│ └── UploadThreadPool.java
└── settings.gradle
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
*.iml
.gradle
/.idea
/screenshots
/local.properties
.DS_Store
/build
/captures
libs/
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2016 jeasonlzy(廖子尧)
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.
================================================
FILE: README.md
================================================

## OkGo - 3.0 震撼来袭, 一个基于okhttp的标准RESTful风格的网络框架
> 工程结构全新优化
支持RxJava
支持RxJava2
支持自定义缓存策略
支持下载管理
支持上传管理
该库部分思想借鉴了以下项目:
* [https://github.com/yanzhenjie/NoHttp](https://github.com/Y0LANDA/NoHttp)
* [https://github.com/square/retrofit](https://github.com/square/retrofit)
在此特别感谢上述作者,喜欢原作的可以去使用原项目。同时欢迎大家下载体验本项目,如果使用过程中遇到什么问题,欢迎反馈。
## 友情链接
本项目中使用的图片选择是我的另一个开源项目
> 完全仿微信的图片选择库,自带矩形图片裁剪和圆形图片裁剪功能,有需要的可以去下载使用。
附上地址:[https://github.com/jeasonlzy/ImagePicker](https://github.com/jeasonlzy/ImagePicker)
本项目中的九宫格控件也是我的开源项目
> 类似QQ空间,微信朋友圈,微博主页等,展示图片的九宫格控件,自动根据图片的数量确定图片大小和控件大小,使用Adapter模式设置图片,对外提供接口回调,使用接口加载图片,支持任意的图片加载框架如:Glide、ImageLoader、xUtils3、Picasso 等,支持点击图片全屏预览大图。
附上地址:[https://github.com/jeasonlzy/NineGridView](https://github.com/jeasonlzy/NineGridView)
## 联系方式
* email: liaojeason@126.com
* QQ群: 489873144
(点击图标,可以直接加入,建议使用QQ群,邮箱使用较少,可能看的不及时)
* 如果遇到问题欢迎在群里提问,个人能力也有限,希望一起学习一起进步。
## 演示

## 未来版本
### [v3.1.x]版本
- 计划分离params参数的具体作用,分为paramsPath,paramsQuery和params,支持url路径动态替换
- 计划支持请求优先级,方便有些重要请求优先进行
- 计划支持自定义线程池,使用自己的线程池管理网络请求
### [v3.2.x]版本
- 计划增加扩展库OkAnno,作用是让okgo支持注解方式请求,具体写法与Retrofit相似,但是更简单方便,也更强大,方便Retrofit用户平滑过渡到OkGo
### 其他功能暂时还没想出来,大家有想法的可以积极加群讨论,或者直接在issue里面提出你的想法,我会第一时间回复。
## 使用
[](https://android-arsenal.com/api?level=14) [](https://developer.android.com/index.html) [](https://www.codacy.com/app/jeasonlzy/okhttp-OkGo?utm_source=github.com&utm_medium=referral&utm_content=jeasonlzy/okhttp-OkGo&utm_campaign=Badge_Grade) [](https://github.com/jeasonlzy/okhttp-OkGo/blob/master/LICENSE) [](https://github.com/jeasonlzy)
[](https://github.com/jeasonlzy/okhttp-OkGo) [](https://github.com/jeasonlzy/okhttp-OkGo) [](https://github.com/jeasonlzy/okhttp-OkGo) [](https://github.com/jeasonlzy/okhttp-OkGo)
Android Studio用户
> 一般来说,只需要添加第一个okgo的核心包即可,其余的三个库根据自己的需要选择添加!!!
```java
//必须使用
compile 'com.lzy.net:okgo:3.0.4'
//以下三个选择添加,okrx和okrx2不能同时使用
compile 'com.lzy.net:okrx:1.0.2'
compile 'com.lzy.net:okrx2:2.0.2'
compile 'com.lzy.net:okserver:2.0.5'
```
Eclipse的用户(赶紧换AS吧),可以选择添加本项目根目录中 `/jar` 目录下的jar包:
> 一般来说,至少需要okhttp、okio、okgo三个jar包,其余的三个扩展jar包根据自己的需要选择添加!!!
必须使用
> [okhttp-3.8.1.jar](https://raw.githubusercontent.com/jeasonlzy/okhttp-OkGo/master/jar/okhttp-3.8.1.jar)
[okio-1.13.0.jar](https://raw.githubusercontent.com/jeasonlzy/okhttp-OkGo/master/jar/okio-1.13.0.jar)
[okgo-3.0.4.jar](https://raw.githubusercontent.com/jeasonlzy/okhttp-OkGo/master/jar/okgo-3.0.4.jar)
以下三个选择添加,okrx和okrx2不能同时使用
> [okrx-1.0.2.jar](https://raw.githubusercontent.com/jeasonlzy/okhttp-OkGo/master/jar/okrx-1.0.2.jar)
[okrx2-2.0.2.jar](https://raw.githubusercontent.com/jeasonlzy/okhttp-OkGo/master/jar/okrx2-2.0.2.jar)
[okserver-2.0.5.jar](https://raw.githubusercontent.com/jeasonlzy/okhttp-OkGo/master/jar/okserver-2.0.5.jar)
## 文档
### 该项目的文档全部以Wiki的形式展示,wiki文档永远与最新版本的库保持同步,如果你发现文档的说明与你的写法不一样,那么请升级到最新版本,重要的事情说三遍
- [点我,点我,我是3.x文档,Wiki文档首页请猛戳这里](https://github.com/jeasonlzy/okhttp-OkGo/wiki)
- [点我,点我,我是3.x文档,Wiki文档首页请猛戳这里](https://github.com/jeasonlzy/okhttp-OkGo/wiki)
- [点我,点我,我是3.x文档,Wiki文档首页请猛戳这里](https://github.com/jeasonlzy/okhttp-OkGo/wiki)
如果你实在不愿意升级到3.x版本,[这里有2.x版本的文档,点击查看](https://github.com/jeasonlzy/okhttp-OkGo/tree/v2.1.4),注意:老版本库的问题将不在维护,所有bug会在最新版本修复,所以建议跟随最新版本的库。
[](https://github.com/jeasonlzy/okhttp-OkGo/wiki)
如果遇到使用问题,解决办法如下:
1. 看上述文档中是否有相关描述
2. 看别人提的issues是否有你的问题,这里面有很多人的提问,[点击这里看别人的提问](https://github.com/jeasonlzy/okhttp-OkGo/issues?q=is%3Aissue+is%3Aclosed)。
3. 如果你感觉是bug,或者有疑问,也欢迎在issues里面提问,我每天都会认真解答,[点击这里提问](https://github.com/jeasonlzy/okhttp-OkGo/issues)。
4. 还有疑问,加入联系方式中的QQ群,大家一起讨论。
如果你不想编译项目,提供了apk供直接运行,方便查看效果,点击图标下载:[](http://7xss53.com1.z0.glb.clouddn.com/file/okgo_v3.0.4.apk)
本项目Demo使用的是我自己的服务器,有时候可能不稳定,网速比较慢时请耐心等待,尴尬呀。。
如果你想查看历史版本信息,请点击图标:[](https://github.com/jeasonlzy/okhttp-OkGo/releases)
如果你使用遇到了问题,首先请看控制台log,如果log无法看出问题,无法确定是该库的bug还是服务端的问题,建议抓包查看网络数据,[详细的抓包方法猛戳这里](https://github.com/jeasonlzy/okhttp-OkGo/wiki#网络抓包)
### 如果你觉得好,对你有过帮助,请给我一点打赏鼓励吧,一分也是爱呀!

## 混淆
okgo, okrx, okrx2, okserver 所有代码均可以混淆,但是由于底层使用的是 okhttp,它不能混淆,所以只需要添加以下混淆代码就可以了
```java
#okhttp
-dontwarn okhttp3.**
-keep class okhttp3.**{*;}
#okio
-dontwarn okio.**
-keep class okio.**{*;}
```
当然如果你确实不需要混淆okgo的代码,可以继续添加以下代码
```java
#okgo
-dontwarn com.lzy.okgo.**
-keep class com.lzy.okgo.**{*;}
#okrx
-dontwarn com.lzy.okrx.**
-keep class com.lzy.okrx.**{*;}
#okrx2
-dontwarn com.lzy.okrx2.**
-keep class com.lzy.okrx2.**{*;}
#okserver
-dontwarn com.lzy.okserver.**
-keep class com.lzy.okserver.**{*;}
```
## Licenses
```
Copyright 2016 jeasonlzy(廖子尧)
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.
```
================================================
FILE: build.gradle
================================================
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7'
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
maven { url "https://jitpack.io" }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
ext {
versionCode = 29
versionName_okgo = '3.0.4'
versionName_okserver = '2.0.5'
versionName_okrx = '1.0.2'
versionName_okrx2 = '2.0.2'
libMinSdkVersion = 14
appMinSdkVersion = 16
targetSdkVersion = 25
compileSdkVersion = 25
buildToolsVersion = '25.0.2'
supportVersion = '25.3.1'
}
================================================
FILE: demo/.gitignore
================================================
/build
================================================
FILE: demo/build.gradle
================================================
apply plugin: 'com.android.application'
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
applicationId "com.lzy.demo"
minSdkVersion rootProject.ext.appMinSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode rootProject.ext.versionCode
versionName rootProject.ext.versionName_okgo
}
signingConfigs {
appkey {
keyAlias 'OkGo'
keyPassword '111111'
storeFile file('../appkey.jks')
storePassword '111111'
}
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
debuggable false
signingConfig signingConfigs.appkey
}
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
debuggable true
signingConfig signingConfigs.appkey
}
}
productFlavors {
miui {
proguardFile './proguard-rules.pro'
signingConfig signingConfigs.appkey
}
qihu360 {
proguardFile './proguard-rules.pro'
signingConfig signingConfigs.appkey
}
}
lintOptions {
abortOnError false
}
packagingOptions {
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/notice'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license'
exclude 'META-INF/license.txt'
exclude 'META-INF/rxjava.properties'
}
}
task makeApk {
doLast {
def versionName = rootProject.ext.versionName_okgo
def appName = "okgo_v${versionName}.apk"
copy {
from "./build/outputs/apk/demo-miui-debug.apk"
into "../"
rename {
appName
}
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile "com.android.support:appcompat-v7:$supportVersion"
compile "com.android.support:design:$supportVersion"
compile "com.android.support:recyclerview-v7:$supportVersion"
compile "com.android.support:cardview-v7:$supportVersion"
compile 'com.github.CymChad:BaseRecyclerViewAdapterHelper:v2.0.7'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.google.code.gson:gson:2.8.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.readystatesoftware.chuck:library:1.0.4'
compile project(':okgo')
compile project(':okrx')
compile project(':okrx2')
compile project(':okserver')
// compile 'com.lzy.net:okgo:3.0.4'
// compile 'com.lzy.net:okrx:1.0.2'
// compile 'com.lzy.net:okrx2:2.0.2'
// compile 'com.lzy.net:okserver:2.0.5'
compile 'com.lzy.widget:ninegridview:0.2.1'
compile 'com.lzy.widget:imagepicker:0.3.2'
compile 'com.lzy.widget:view-core:0.2.1'
}
================================================
FILE: demo/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in E:\Android\SDK/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
#---------------------------------1.实体类---------------------------------
-keep class com.lzy.okhttpdemo.Bean.** { *; }
#-------------------------------------------------------------------------
#---------------------------------2.第三方包-------------------------------
#okgo
#-dontwarn com.lzy.okgo.**
#-keep class com.lzy.okgo.**{*;}
#okrx
#-dontwarn com.lzy.okrx.**
#-keep class com.lzy.okrx.**{*;}
#okserver
#-dontwarn com.lzy.okserver.**
#-keep class com.lzy.okserver.**{*;}
#okhttp
-dontwarn okhttp3.**
-keep class okhttp3.**{*;}
-keepattributes SourceFile,LineNumberTable
-keep class com.parse.*{ *; }
-dontwarn com.parse.**
-dontwarn com.squareup.picasso.**
-keepclasseswithmembernames class * {
native ;
}
#okio
-dontwarn okio.**
-keep class okio.**{*;}
#rxjava
-dontwarn sun.misc.**
-keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {
long producerIndex;
long consumerIndex;
}
-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
rx.internal.util.atomic.LinkedQueueNode producerNode;
}
-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueConsumerNodeRef {
rx.internal.util.atomic.LinkedQueueNode consumerNode;
}
#imagepicker
-dontwarn com.lzy.imagepicker.**
-keep class com.lzy.imagepicker.**{*;}
#imagepicker
-dontwarn com.lzy.widget.**
-keep class com.lzy.widget.**{*;}
#butterknife
-keep class butterknife.** { *; }
-dontwarn butterknife.internal.**
-keep class **$$ViewBinder { *; }
-keepclasseswithmembernames class * {
@butterknife.* ;
}
-keepclasseswithmembernames class * {
@butterknife.* ;
}
#gson
-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.stream.**{ *; }
-keep class com.google.gson.examples.android.model.**{ *; }
-keep class com.google.gson.**{ *;}
#eventBus
-keepattributes *Annotation*
-keepclassmembers class ** {
@org.greenrobot.eventbus.Subscribe ;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
(java.lang.Throwable);
}
-keepclassmembers class ** {
public void onEvent*(**);
}
#glide
-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
**[] $VALUES;
public *;
}
#log4j
#-libraryjars log4j-1.2.17.jar
-dontwarn org.apache.log4j.**
-keep class org.apache.log4j.** { *;}
#------------------------------------------------------------------------
#---------------------------------3.与js互相调用的类------------------------
#-keepclasseswithmembers class com.demo.login.bean.ui.MainActivity$JSInterface {
# ;
#}
#------------------------------------------------------------------------
#---------------------------------4.反射相关的类和方法-----------------------
#------------------------------------------------------------------------
#---------------------------------基本指令区-------------------------------
#代码混淆的压缩比例,值在0-7之间
-optimizationpasses 5
#混淆后类名都为小写
-dontusemixedcaseclassnames
#指定不去忽略非公共的库的类
-dontskipnonpubliclibraryclasses
#指定不去忽略非公共的库的类的成员
-dontskipnonpubliclibraryclassmembers
#不做预校验的操作
-dontpreverify
#生成原类名和混淆后的类名的映射文件
-verbose
-printmapping proguardMapping.txt
#指定混淆是采用的算法
-optimizations !code/simplification/cast,!field/*,!class/merging/*
#不混淆Annotation
-keepattributes *Annotation*,InnerClasses
#不混淆泛型
-keepattributes Signature
#抛出异常时保留代码行号
-keepattributes SourceFile,LineNumberTable
#------------------------------------------------------------------------
#-keep class XXXX 保留类名不变,也就是类名不混淆,而类中的成员名不保证。当然也可以是继承XXX类的所有类名不混淆
#-keepclasseswithmembers class XXXX 保留类名和成员名,当然也可以是类中特定方法
#---------------------------------默认保留区-------------------------------
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class * extends android.view.View
-keep public class com.android.vending.licensing.ILicensingService
-keep public class * extends android.support.**
-keep public class * extends android.app.Fragment
-dontwarn android.support.**
-keep class android.support.** {*;}
#自定义控件不要混淆
-keep public class * extends android.view.View {*;}
#adapter不能混淆
-keep public class * extends android.widget.BaseAdapter {*;}
#CusorAdapter不混淆
-keep public class * extends android.widget.CusorAdapter{*;}
-keepclasseswithmembernames class * {
native ;
}
-keepclassmembers class * extends android.app.Activity{
public void *(android.view.View);
}
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep public class * extends android.view.View{
*** get*();
void set*(***);
public (android.content.Context);
public (android.content.Context, android.util.AttributeSet);
public (android.content.Context, android.util.AttributeSet, int);
}
-keepclasseswithmembers class * {
public (android.content.Context, android.util.AttributeSet);
public (android.content.Context, android.util.AttributeSet, int);
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
-keep class * extends java.util.ListResourceBundle {
protected Object[][] getContents();
}
-keepnames class * implements java.io.Serializable
-keepclassmembers class * implements java.io.Serializable {*;}
-keep class **.R$* {*;}
-keepclassmembers class * {
void *(**On*Event);
}
#----------------------------------------------------------------------------
#---------------------------------webview------------------------------------
-keepclassmembers class fqcn.of.javascript.interface.for.Webview {
public *;
}
-keepclassmembers class * extends android.webkit.WebViewClient {
public void *(android.webkit.WebView, java.lang.String, android.graphics.Bitmap);
public boolean *(android.webkit.WebView, java.lang.String);
}
-keepclassmembers class * extends android.webkit.WebViewClient {
public void *(android.webkit.WebView, jav.lang.String);
}
#----------------------------------------------------------------------------
================================================
FILE: demo/src/main/AndroidManifest.xml
================================================
================================================
FILE: demo/src/main/java/com/lzy/demo/GApp.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo;
import android.app.Application;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.DBCookieStore;
import com.lzy.okgo.https.HttpsUtils;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
/**
* ================================================
* 作 者:廖子尧 github 地址 https://github.com/jeasonlzy/
* 版 本:1.0
* 创建日期:2015/9/23
* 描 述:
* 修订历史:
* ================================================
*/
public class GApp extends Application {
@Override
public void onCreate() {
super.onCreate();
// System.setProperty("http.proxyHost", "192.168.1.104"); //个人测试网络时用的,删掉即可
// System.setProperty("http.proxyPort", "8888");
initOkGo();
}
private void initOkGo() {
//---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------//
HttpHeaders headers = new HttpHeaders();
headers.put("commonHeaderKey1", "commonHeaderValue1"); //header不支持中文,不允许有特殊字符
headers.put("commonHeaderKey2", "commonHeaderValue2");
HttpParams params = new HttpParams();
params.put("commonParamsKey1", "commonParamsValue1"); //param支持中文,直接传,不要自己编码
params.put("commonParamsKey2", "这里支持中文参数");
//----------------------------------------------------------------------------------------//
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//log相关
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY); //log打印级别,决定了log显示的详细程度
loggingInterceptor.setColorLevel(Level.INFO); //log颜色级别,决定了log在控制台显示的颜色
builder.addInterceptor(loggingInterceptor); //添加OkGo默认debug日志
//第三方的开源库,使用通知显示当前请求的log,不过在做文件下载的时候,这个库好像有问题,对文件判断不准确
//builder.addInterceptor(new ChuckInterceptor(this));
//超时时间设置,默认60秒
builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS); //全局的读取超时时间
builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS); //全局的写入超时时间
builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS); //全局的连接超时时间
//自动管理cookie(或者叫session的保持),以下几种任选其一就行
//builder.cookieJar(new CookieJarImpl(new SPCookieStore(this))); //使用sp保持cookie,如果cookie不过期,则一直有效
builder.cookieJar(new CookieJarImpl(new DBCookieStore(this))); //使用数据库保持cookie,如果cookie不过期,则一直有效
//builder.cookieJar(new CookieJarImpl(new MemoryCookieStore())); //使用内存保持cookie,app退出后,cookie消失
//https相关设置,以下几种方案根据需要自己设置
//方法一:信任所有证书,不安全有风险
HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
//方法二:自定义信任规则,校验服务端证书
HttpsUtils.SSLParams sslParams2 = HttpsUtils.getSslSocketFactory(new SafeTrustManager());
//方法三:使用预埋证书,校验服务端证书(自签名证书)
//HttpsUtils.SSLParams sslParams3 = HttpsUtils.getSslSocketFactory(getAssets().open("srca.cer"));
//方法四:使用bks证书和密码管理客户端证书(双向认证),使用预埋证书,校验服务端证书(自签名证书)
//HttpsUtils.SSLParams sslParams4 = HttpsUtils.getSslSocketFactory(getAssets().open("xxx.bks"), "123456", getAssets().open("yyy.cer"));
builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
//配置https的域名匹配规则,详细看demo的初始化介绍,不需要就不要加入,使用不当会导致https握手失败
builder.hostnameVerifier(new SafeHostnameVerifier());
// 其他统一的配置
// 详细说明看GitHub文档:https://github.com/jeasonlzy/
OkGo.getInstance().init(this) //必须调用初始化
.setOkHttpClient(builder.build()) //建议设置OkHttpClient,不设置会使用默认的
.setCacheMode(CacheMode.NO_CACHE) //全局统一缓存模式,默认不使用缓存,可以不传
.setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE) //全局统一缓存时间,默认永不过期,可以不传
.setRetryCount(3) //全局统一超时重连次数,默认为三次,那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0
.addCommonHeaders(headers) //全局公共头
.addCommonParams(params); //全局公共参数
}
/**
* 这里只是我谁便写的认证规则,具体每个业务是否需要验证,以及验证规则是什么,请与服务端或者leader确定
* 这里只是我谁便写的认证规则,具体每个业务是否需要验证,以及验证规则是什么,请与服务端或者leader确定
* 这里只是我谁便写的认证规则,具体每个业务是否需要验证,以及验证规则是什么,请与服务端或者leader确定
* 重要的事情说三遍,以下代码不要直接使用
*/
private class SafeTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
for (X509Certificate certificate : chain) {
certificate.checkValidity(); //检查证书是否过期,签名是否通过等
}
} catch (Exception e) {
throw new CertificateException(e);
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
/**
* 这里只是我谁便写的认证规则,具体每个业务是否需要验证,以及验证规则是什么,请与服务端或者leader确定
* 这里只是我谁便写的认证规则,具体每个业务是否需要验证,以及验证规则是什么,请与服务端或者leader确定
* 这里只是我谁便写的认证规则,具体每个业务是否需要验证,以及验证规则是什么,请与服务端或者leader确定
* 重要的事情说三遍,以下代码不要直接使用
*/
private class SafeHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
//验证主机名是否匹配
//return hostname.equals("server.jeasonlzy.com");
return true;
}
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/MainActivity.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Pair;
import android.view.View;
import com.lzy.demo.base.BaseActivity;
import com.lzy.demo.okdownload.OkDownloadFragment;
import com.lzy.demo.okgo.OkGoFragment;
import com.lzy.demo.okrx2.OkRx2Fragment;
import com.lzy.demo.okrx2.OkRxFragment;
import com.lzy.demo.okupload.OkUploadFragment;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.OnClick;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public class MainActivity extends BaseActivity {
@Bind(R.id.toolbar) Toolbar toolbar;
@Bind(R.id.viewPager) ViewPager viewPager;
@Bind(R.id.tab) TabLayout tab;
private List> items;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initToolBar(toolbar, false, "");
items = new ArrayList<>();
items.add(new Pair("OkGo", new OkGoFragment()));
items.add(new Pair("打赏", new PayFragment()));
items.add(new Pair("OkRx2", new OkRx2Fragment()));
items.add(new Pair("OkRx", new OkRxFragment()));
items.add(new Pair("OkDownload", new OkDownloadFragment()));
items.add(new Pair("OkUpload", new OkUploadFragment()));
viewPager.setAdapter(new MainAdapter(getSupportFragmentManager()));
tab.setupWithViewPager(viewPager);
}
@OnClick(R.id.fab)
public void fab(View view) {
WebActivity.runActivity(this, "我的Github,欢迎star", "https://github.com/jeasonlzy");
}
@Override
protected boolean translucentStatusBar() {
return true;
}
private class MainAdapter extends FragmentPagerAdapter {
MainAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return items.get(position).second;
}
@Override
public int getCount() {
return items.size();
}
@Override
public CharSequence getPageTitle(int position) {
return items.get(position).first;
}
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/PayFragment.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.lzy.demo.base.BaseFragment;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:2017/6/9
* 描 述:
* 修订历史:
* ================================================
*/
public class PayFragment extends BaseFragment {
@Override
protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_pay, container, false);
}
@Override
protected void initData() {
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/WebActivity.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import com.lzy.demo.base.BaseActivity;
import butterknife.Bind;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public class WebActivity extends BaseActivity {
public final static String URL = "url";
public final static String TITLE = "title";
@Bind(R.id.toolbar) Toolbar toolbar;
@Bind(R.id.pb) ProgressBar pb;
@Bind(R.id.webView) WebView webView;
public static void runActivity(Context context, String title, String url) {
Intent intent = new Intent(context, WebActivity.class);
intent.putExtra(URL, url);
intent.putExtra(TITLE, title);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
String url = getIntent().getStringExtra(URL);
String title = getIntent().getStringExtra(TITLE);
initToolBar(toolbar, true, title);
pb.setMax(100);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
pb.setProgress(newProgress);
if (newProgress >= 100) {
pb.setVisibility(View.GONE);
}
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.loadUrl(url);
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/base/BaseActivity.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.base;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.lzy.demo.R;
import com.lzy.imagepicker.view.SystemBarTintManager;
import butterknife.ButterKnife;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public abstract class BaseActivity extends AppCompatActivity {
@SuppressWarnings("unchecked")
public T findView(int id) {
return (T) findViewById(id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initSystemBarTint();
}
@Override
public void setContentView(@LayoutRes int layoutResID) {
super.setContentView(layoutResID);
ButterKnife.bind(this);
}
@Override
public void setContentView(View view) {
super.setContentView(view);
ButterKnife.bind(this);
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
super.setContentView(view, params);
ButterKnife.bind(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:// 点击返回图标事件
finish();
default:
return super.onOptionsItemSelected(item);
}
}
/** 子类可以重写改变状态栏颜色 */
protected int setStatusBarColor() {
return getColorPrimary();
}
/** 子类可以重写决定是否使用透明状态栏 */
protected boolean translucentStatusBar() {
return false;
}
/** 设置状态栏颜色 */
protected void initSystemBarTint() {
Window window = getWindow();
if (translucentStatusBar()) {
// 设置状态栏全透明
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
return;
}
// 沉浸式状态栏
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//5.0以上使用原生方法
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(setStatusBarColor());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//4.4-5.0使用三方工具类,有些4.4的手机有问题,这里为演示方便,不使用沉浸式
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintColor(setStatusBarColor());
}
}
/** 获取主题色 */
public int getColorPrimary() {
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
return typedValue.data;
}
/** 获取深主题色 */
public int getDarkColorPrimary() {
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
return typedValue.data;
}
/** 初始化 Toolbar */
public void initToolBar(Toolbar toolbar, boolean homeAsUpEnabled, String title) {
toolbar.setTitle(title);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(homeAsUpEnabled);
}
public void initToolBar(Toolbar toolbar, boolean homeAsUpEnabled, int resTitle) {
initToolBar(toolbar, homeAsUpEnabled, getString(resTitle));
}
public void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
private ProgressDialog dialog;
public void showLoading() {
if (dialog != null && dialog.isShowing()) return;
dialog = new ProgressDialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCanceledOnTouchOutside(false);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("请求网络中...");
dialog.show();
}
public void dismissLoading() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
public void displayImage(String url, ImageView imageView) {
Glide.with(getApplicationContext())//
.load(url)//
.error(R.mipmap.ic_launcher)//
.into(imageView);
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/base/BaseDetailActivity.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.base;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.lzy.demo.R;
import com.lzy.demo.utils.Convert;
import com.lzy.okgo.model.Response;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
import okhttp3.Call;
import okhttp3.Headers;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public abstract class BaseDetailActivity extends BaseActivity {
protected ActionBar actionBar;
protected TextView requestState;
protected TextView requestHeaders;
protected TextView responseData;
protected TextView responseHeader;
protected FrameLayout rootContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
getDelegate().setContentView(R.layout.activity_base);
Window window = getWindow();
requestState = (TextView) window.findViewById(R.id.requestState);
requestHeaders = (TextView) window.findViewById(R.id.requestHeaders);
responseData = (TextView) window.findViewById(R.id.responseData);
responseHeader = (TextView) window.findViewById(R.id.responseHeader);
rootContent = (FrameLayout) window.findViewById(R.id.content);
onActivityCreate(savedInstanceState);
}
protected abstract void onActivityCreate(Bundle savedInstanceState);
@Override
public void setTitle(CharSequence title) {
if (actionBar != null) actionBar.setTitle(title);
}
@Override
public void setTitle(int titleId) {
if (actionBar != null) actionBar.setTitle(titleId);
}
@Override
public View findViewById(int id) {
return rootContent.findViewById(id);
}
private void clearContentView() {
rootContent.removeAllViews();
}
@Override
public void setContentView(int layoutResID) {
clearContentView();
getLayoutInflater().inflate(layoutResID, rootContent, true);
}
@Override
public void setContentView(View view) {
clearContentView();
rootContent.addView(view);
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
clearContentView();
rootContent.addView(view, params);
}
protected void handleResponse(T data) {
Response response = new Response<>();
response.setBody(data);
handleResponse(response);
}
protected void handleResponse(Response response) {
StringBuilder sb;
Call call = response.getRawCall();
if (call != null) {
requestState.setText("请求成功 请求方式:" + call.request().method() + "\n" + "url:" + call.request().url());
Headers requestHeadersString = call.request().headers();
Set requestNames = requestHeadersString.names();
sb = new StringBuilder();
for (String name : requestNames) {
sb.append(name).append(" : ").append(requestHeadersString.get(name)).append("\n");
}
requestHeaders.setText(sb.toString());
} else {
requestState.setText("--");
requestHeaders.setText("--");
}
T body = response.body();
if (body == null) {
responseData.setText("--");
} else {
if (body instanceof String) {
responseData.setText((String) body);
} else if (body instanceof List) {
sb = new StringBuilder();
List list = (List) body;
for (Object obj : list) {
sb.append(obj.toString()).append("\n");
}
responseData.setText(sb.toString());
} else if (body instanceof Set) {
sb = new StringBuilder();
Set set = (Set) body;
for (Object obj : set) {
sb.append(obj.toString()).append("\n");
}
responseData.setText(sb.toString());
} else if (body instanceof Map) {
sb = new StringBuilder();
Map map = (Map) body;
Set keySet = map.keySet();
for (Object key : keySet) {
sb.append(key.toString()).append(" : ").append(map.get(key)).append("\n");
}
responseData.setText(sb.toString());
} else if (body instanceof File) {
File file = (File) body;
responseData.setText("数据内容即为文件内容\n下载文件路径:" + file.getAbsolutePath());
} else if (body instanceof Bitmap) {
responseData.setText("图片的内容即为数据");
} else {
responseData.setText(Convert.formatJson(body));
}
}
okhttp3.Response rawResponse = response.getRawResponse();
if (rawResponse != null) {
Headers responseHeadersString = rawResponse.headers();
Set names = responseHeadersString.names();
sb = new StringBuilder();
sb.append("url : ").append(rawResponse.request().url()).append("\n\n");
sb.append("stateCode : ").append(rawResponse.code()).append("\n");
for (String name : names) {
sb.append(name).append(" : ").append(responseHeadersString.get(name)).append("\n");
}
responseHeader.setText(sb.toString());
} else {
responseHeader.setText("--");
}
}
protected void handleError() {
Response response = new Response<>();
handleResponse(response);
}
protected void handleError(Response response) {
if (response == null) return;
if (response.getException() != null) response.getException().printStackTrace();
StringBuilder sb;
Call call = response.getRawCall();
if (call != null) {
requestState.setText("请求失败 请求方式:" + call.request().method() + "\n" + "url:" + call.request().url());
Headers requestHeadersString = call.request().headers();
Set requestNames = requestHeadersString.names();
sb = new StringBuilder();
for (String name : requestNames) {
sb.append(name).append(" : ").append(requestHeadersString.get(name)).append("\n");
}
requestHeaders.setText(sb.toString());
} else {
requestState.setText("--");
requestHeaders.setText("--");
}
responseData.setText("--");
okhttp3.Response rawResponse = response.getRawResponse();
if (rawResponse != null) {
Headers responseHeadersString = rawResponse.headers();
Set names = responseHeadersString.names();
sb = new StringBuilder();
sb.append("stateCode : ").append(rawResponse.code()).append("\n");
for (String name : names) {
sb.append(name).append(" : ").append(responseHeadersString.get(name)).append("\n");
}
responseHeader.setText(sb.toString());
} else {
responseHeader.setText("--");
}
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/base/BaseFragment.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.base;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* 若把初始化内容放到initData实现,就是采用Lazy方式加载的Fragment
* 若不需要Lazy加载则initData方法内留空,初始化内容放到initViews即可
* -
* -注1: 如果是与ViewPager一起使用,调用的是setUserVisibleHint。
* ------可以调用mViewPager.setOffscreenPageLimit(size),若设置了该属性 则viewpager会缓存指定数量的Fragment
* -注2: 如果是通过FragmentTransaction的show和hide的方法来控制显示,调用的是onHiddenChanged.
* -注3: 针对初始就show的Fragment 为了触发onHiddenChanged事件 达到lazy效果 需要先hide再show
*/
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public abstract class BaseFragment extends Fragment {
protected String fragmentTitle; //fragment标题
private boolean isVisible; //是否可见状态
private boolean isPrepared; //标志位,View已经初始化完成。
private boolean isFirstLoad = true; //是否第一次加载
protected LayoutInflater inflater;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
this.inflater = inflater;
isFirstLoad = true;
View view = initView(inflater, container, savedInstanceState);
isPrepared = true;
lazyLoad();
return view;
}
/** 如果是与ViewPager一起使用,调用的是setUserVisibleHint */
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getUserVisibleHint()) {
isVisible = true;
onVisible();
} else {
isVisible = false;
onInvisible();
}
}
/**
* 如果是通过FragmentTransaction的show和hide的方法来控制显示,调用的是onHiddenChanged.
* 若是初始就show的Fragment 为了触发该事件 需要先hide再show
*/
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (!hidden) {
isVisible = true;
onVisible();
} else {
isVisible = false;
onInvisible();
}
}
protected void onVisible() {
lazyLoad();
}
protected void onInvisible() {
}
protected void lazyLoad() {
if (!isPrepared || !isVisible || !isFirstLoad) {
return;
}
isFirstLoad = false;
initData();
}
protected abstract View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
protected abstract void initData();
public String getTitle() {
return TextUtils.isEmpty(fragmentTitle) ? "" : fragmentTitle;
}
public void setTitle(String title) {
fragmentTitle = title;
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/base/BaseRecyclerAdapter.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.base;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public abstract class BaseRecyclerAdapter extends RecyclerView.Adapter {
protected Context mContext;
protected List mDatas;
protected LayoutInflater inflater;
public BaseRecyclerAdapter(Context context) {
this.mContext = context;
this.mDatas = new ArrayList<>();
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public BaseRecyclerAdapter(Context context, List datas) {
if (datas == null) datas = new ArrayList<>();
this.mContext = context;
this.mDatas = datas;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public BaseRecyclerAdapter(Context context, T[] datas) {
this.mContext = context;
this.mDatas = new ArrayList();
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Collections.addAll(mDatas, datas);
}
@Override
public int getItemCount() {
return mDatas == null ? 0 : mDatas.size();
}
/** 更新数据,替换原有数据 */
public void updateItems(List items) {
mDatas = items;
notifyDataSetChanged();
}
/** 插入一条数据 */
public void addItem(T item) {
mDatas.add(0, item);
notifyItemInserted(0);
}
/** 插入一条数据 */
public void addItem(T item, int position) {
position = Math.min(position, mDatas.size());
mDatas.add(position, item);
notifyItemInserted(position);
}
/** 在列表尾添加一串数据 */
public void addItems(List items) {
int start = mDatas.size();
mDatas.addAll(items);
notifyItemRangeChanged(start, items.size());
}
/** 移除一条数据 */
public void removeItem(int position) {
if (position > mDatas.size() - 1) {
return;
}
mDatas.remove(position);
notifyItemRemoved(position);
}
/** 移除一条数据 */
public void removeItem(T item) {
int position = 0;
ListIterator iterator = mDatas.listIterator();
while (iterator.hasNext()) {
T next = iterator.next();
if (next == item) {
iterator.remove();
notifyItemRemoved(position);
}
position++;
}
}
/** 清除所有数据 */
public void removeAllItems() {
mDatas.clear();
notifyDataSetChanged();
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/base/BaseRxDetailActivity.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.base;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/10/1
* 描 述:统一管理所有的订阅生命周期
* 修订历史:
* ================================================
*/
public abstract class BaseRxDetailActivity extends BaseDetailActivity {
private CompositeDisposable compositeDisposable;
public void addDisposable(Disposable disposable) {
if (compositeDisposable == null) {
compositeDisposable = new CompositeDisposable();
}
compositeDisposable.add(disposable);
}
public void dispose() {
if (compositeDisposable != null) compositeDisposable.dispose();
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/base/DividerItemDecoration.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.base;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)
* 版 本:1.0
* 创建日期:2016/4/7
* 描 述:我的Github地址 https://github.com/jeasonlzy
* 修订历史:
* ================================================
*/
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
private Drawable mDivider;
private int mOrientation;
public DividerItemDecoration(Context context, int orientation) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
setOrientation(orientation);
}
public void setOrientation(int orientation) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw new IllegalArgumentException("invalid orientation");
}
mOrientation = orientation;
}
@Override
public void onDraw(Canvas c, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}
}
public void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
public void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
final int left = child.getRight() + params.rightMargin;
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
@Override
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/base/MainFragment.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.base;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.lzy.demo.R;
import com.lzy.demo.model.ItemModel;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:2017/6/9
* 描 述:
* 修订历史:
* ================================================
*/
public abstract class MainFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
@Bind(R.id.refreshLayout) SwipeRefreshLayout refreshLayout;
@Bind(R.id.recyclerView) RecyclerView recyclerView;
protected Context context;
private MainAdapter adapter;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
@Override
protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.item_refresh, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onRefresh() {
setRefreshing(false);
}
@Override
public void onLoadMoreRequested() {
refreshLayout.postDelayed(new Runnable() {
@Override
public void run() {
adapter.loadComplete();
}
}, 500);
}
@Override
protected void initData() {
List items = new ArrayList<>();
fillData(items);
adapter = new MainAdapter(items);
adapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
adapter.isFirstOnly(false);
adapter.setOnLoadMoreListener(this);
refreshLayout.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
refreshLayout.setOnRefreshListener(this);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(context, LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(adapter);
}
public abstract void fillData(List items);
public abstract void onItemClick(int position);
private class MainAdapter extends BaseQuickAdapter {
MainAdapter(List data) {
super(R.layout.item_main_list, data);
}
@Override
protected void convert(final BaseViewHolder baseViewHolder, ItemModel itemModel) {
baseViewHolder.setText(R.id.title, itemModel.title);
baseViewHolder.setText(R.id.des, itemModel.des);
baseViewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onItemClick(baseViewHolder.getAdapterPosition());
}
});
}
}
public void setRefreshing(final boolean refreshing) {
refreshLayout.post(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(refreshing);
}
});
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/callback/BitmapDialogCallback.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.callback;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.view.Window;
import com.lzy.okgo.callback.BitmapCallback;
import com.lzy.okgo.request.base.Request;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:2016/1/14
* 描 述:请求图图片的时候显示对话框
* 修订历史:
* ================================================
*/
public abstract class BitmapDialogCallback extends BitmapCallback {
private ProgressDialog dialog;
public BitmapDialogCallback(Activity activity) {
super(1000, 1000);
dialog = new ProgressDialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCanceledOnTouchOutside(false);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("请求网络中...");
}
@Override
public void onStart(Request request) {
if (dialog != null && !dialog.isShowing()) {
dialog.show();
}
}
@Override
public void onFinish() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/callback/DialogCallback.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.callback;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Window;
import com.lzy.okgo.request.base.Request;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:2016/1/14
* 描 述:对于网络请求是否需要弹出进度对话框
* 修订历史:
* ================================================
*/
public abstract class DialogCallback extends JsonCallback {
private ProgressDialog dialog;
private void initDialog(Activity activity) {
dialog = new ProgressDialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCanceledOnTouchOutside(false);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("请求网络中...");
}
public DialogCallback(Activity activity) {
super();
initDialog(activity);
}
@Override
public void onStart(Request request) {
if (dialog != null && !dialog.isShowing()) {
dialog.show();
}
}
@Override
public void onFinish() {
//网络请求结束后关闭对话框
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/callback/EncryptCallback.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.callback;
import com.lzy.demo.utils.MD5Utils;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.request.base.Request;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:2017/6/11
* 描 述:
* 修订历史:
* ================================================
*/
public abstract class EncryptCallback extends JsonCallback {
private static final Random RANDOM = new Random();
private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyz";
@Override
public void onStart(Request request) {
super.onStart(request);
//以下是示例加密代码,根据自己的业务需求和服务器的配合,算法自行决定,这里只是demo,不能用于商业项目
sign(request.getParams());
}
/**
* 针对URL进行签名,关于这几个参数的作用,详细请看
* http://www.cnblogs.com/bestzrz/archive/2011/09/03/2164620.html
*/
private void sign(HttpParams params) {
params.put("nonce", getRndStr(6 + RANDOM.nextInt(8)));
params.put("timestamp", "" + (System.currentTimeMillis() / 1000L));
StringBuilder sb = new StringBuilder();
Map map = new HashMap<>();
for (Map.Entry> entry : params.urlParamsMap.entrySet()) {
map.put(entry.getKey(), entry.getValue().get(0));
}
for (Map.Entry entry : getSortedMapByKey(map).entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
sb.delete(sb.length() - 1, sb.length());
String sign = MD5Utils.encode(sb.toString());
params.put("sign", sign);
}
/** 获取随机数 */
private String getRndStr(int length) {
StringBuilder sb = new StringBuilder();
char ch;
for (int i = 0; i < length; i++) {
ch = CHARS.charAt(RANDOM.nextInt(CHARS.length()));
sb.append(ch);
}
return sb.toString();
}
/** 按照key的自然顺序进行排序,并返回 */
private Map getSortedMapByKey(Map map) {
Comparator comparator = new Comparator() {
@Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs);
}
};
Map treeMap = new TreeMap<>(comparator);
for (Map.Entry entry : map.entrySet()) {
treeMap.put(entry.getKey(), entry.getValue());
}
return treeMap;
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/callback/JsonCallback.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.callback;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.request.base.Request;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import okhttp3.Response;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:2016/1/14
* 描 述:默认将返回的数据解析成需要的Bean,可以是 BaseBean,String,List,Map
* 修订历史:
* ================================================
*/
public abstract class JsonCallback extends AbsCallback {
private Type type;
private Class clazz;
public JsonCallback() {
}
public JsonCallback(Type type) {
this.type = type;
}
public JsonCallback(Class clazz) {
this.clazz = clazz;
}
@Override
public void onStart(Request request) {
super.onStart(request);
// 主要用于在所有请求之前添加公共的请求头或请求参数
// 例如登录授权的 token
// 使用的设备信息
// 可以随意添加,也可以什么都不传
// 还可以在这里对所有的参数进行加密,均在这里实现
request.headers("header1", "HeaderValue1")//
.params("params1", "ParamsValue1")//
.params("token", "3215sdf13ad1f65asd4f3ads1f");
}
/**
* 该方法是子线程处理,不能做ui相关的工作
* 主要作用是解析网络返回的 response 对象,生产onSuccess回调中需要的数据对象
* 这里的解析工作不同的业务逻辑基本都不一样,所以需要自己实现,以下给出的时模板代码,实际使用根据需要修改
*/
@Override
public T convertResponse(Response response) throws Throwable {
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
//详细自定义的原理和文档,看这里: https://github.com/jeasonlzy/okhttp-OkGo/wiki/JsonCallback
if (type == null) {
if (clazz == null) {
Type genType = getClass().getGenericSuperclass();
type = ((ParameterizedType) genType).getActualTypeArguments()[0];
} else {
JsonConvert convert = new JsonConvert<>(clazz);
return convert.convertResponse(response);
}
}
JsonConvert convert = new JsonConvert<>(type);
return convert.convertResponse(response);
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/callback/JsonConvert.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.callback;
import com.google.gson.stream.JsonReader;
import com.lzy.demo.model.LzyResponse;
import com.lzy.demo.model.SimpleResponse;
import com.lzy.demo.utils.Convert;
import com.lzy.okgo.convert.Converter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public class JsonConvert implements Converter {
private Type type;
private Class clazz;
public JsonConvert() {
}
public JsonConvert(Type type) {
this.type = type;
}
public JsonConvert(Class clazz) {
this.clazz = clazz;
}
/**
* 该方法是子线程处理,不能做ui相关的工作
* 主要作用是解析网络返回的 response 对象,生成onSuccess回调中需要的数据对象
* 这里的解析工作不同的业务逻辑基本都不一样,所以需要自己实现,以下给出的时模板代码,实际使用根据需要修改
*/
@Override
public T convertResponse(Response response) throws Throwable {
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
// 如果你对这里的代码原理不清楚,可以看这里的详细原理说明: https://github.com/jeasonlzy/okhttp-OkGo/wiki/JsonCallback
// 如果你对这里的代码原理不清楚,可以看这里的详细原理说明: https://github.com/jeasonlzy/okhttp-OkGo/wiki/JsonCallback
// 如果你对这里的代码原理不清楚,可以看这里的详细原理说明: https://github.com/jeasonlzy/okhttp-OkGo/wiki/JsonCallback
if (type == null) {
if (clazz == null) {
// 如果没有通过构造函数传进来,就自动解析父类泛型的真实类型(有局限性,继承后就无法解析到)
Type genType = getClass().getGenericSuperclass();
type = ((ParameterizedType) genType).getActualTypeArguments()[0];
} else {
return parseClass(response, clazz);
}
}
if (type instanceof ParameterizedType) {
return parseParameterizedType(response, (ParameterizedType) type);
} else if (type instanceof Class) {
return parseClass(response, (Class>) type);
} else {
return parseType(response, type);
}
}
private T parseClass(Response response, Class> rawType) throws Exception {
if (rawType == null) return null;
ResponseBody body = response.body();
if (body == null) return null;
JsonReader jsonReader = new JsonReader(body.charStream());
if (rawType == String.class) {
//noinspection unchecked
return (T) body.string();
} else if (rawType == JSONObject.class) {
//noinspection unchecked
return (T) new JSONObject(body.string());
} else if (rawType == JSONArray.class) {
//noinspection unchecked
return (T) new JSONArray(body.string());
} else {
T t = Convert.fromJson(jsonReader, rawType);
response.close();
return t;
}
}
private T parseType(Response response, Type type) throws Exception {
if (type == null) return null;
ResponseBody body = response.body();
if (body == null) return null;
JsonReader jsonReader = new JsonReader(body.charStream());
// 泛型格式如下: new JsonCallback<任意JavaBean>(this)
T t = Convert.fromJson(jsonReader, type);
response.close();
return t;
}
private T parseParameterizedType(Response response, ParameterizedType type) throws Exception {
if (type == null) return null;
ResponseBody body = response.body();
if (body == null) return null;
JsonReader jsonReader = new JsonReader(body.charStream());
Type rawType = type.getRawType(); // 泛型的实际类型
Type typeArgument = type.getActualTypeArguments()[0]; // 泛型的参数
if (rawType != LzyResponse.class) {
// 泛型格式如下: new JsonCallback<外层BaseBean<内层JavaBean>>(this)
T t = Convert.fromJson(jsonReader, type);
response.close();
return t;
} else {
if (typeArgument == Void.class) {
// 泛型格式如下: new JsonCallback>(this)
SimpleResponse simpleResponse = Convert.fromJson(jsonReader, SimpleResponse.class);
response.close();
//noinspection unchecked
return (T) simpleResponse.toLzyResponse();
} else {
// 泛型格式如下: new JsonCallback>(this)
LzyResponse lzyResponse = Convert.fromJson(jsonReader, type);
response.close();
int code = lzyResponse.code;
//这里的0是以下意思
//一般来说服务器会和客户端约定一个数表示成功,其余的表示失败,这里根据实际情况修改
if (code == 0) {
//noinspection unchecked
return (T) lzyResponse;
} else if (code == 104) {
throw new IllegalStateException("用户授权信息无效");
} else if (code == 105) {
throw new IllegalStateException("用户收取信息已过期");
} else {
//直接将服务端的错误信息抛出,onError中可以获取
throw new IllegalStateException("错误代码:" + code + ",错误信息:" + lzyResponse.msg);
}
}
}
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/callback/StringDialogCallback.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.callback;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Window;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.base.Request;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)
* 版 本:1.0
* 创建日期:2016/4/8
* 描 述:我的Github地址 https://github.com/jeasonlzy
* 修订历史:
* ================================================
*/
public abstract class StringDialogCallback extends StringCallback {
private ProgressDialog dialog;
public StringDialogCallback(Activity activity) {
dialog = new ProgressDialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCanceledOnTouchOutside(false);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("请求网络中...");
}
@Override
public void onStart(Request request) {
if (dialog != null && !dialog.isShowing()) {
dialog.show();
}
}
@Override
public void onFinish() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/model/ApkModel.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.model;
import java.io.Serializable;
import java.util.Random;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public class ApkModel implements Serializable {
private static final long serialVersionUID = 2072893447591548402L;
public String name;
public String url;
public String iconUrl;
public int priority;
public ApkModel() {
Random random = new Random();
priority = random.nextInt(100);
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/model/GankModel.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/1
* 描 述:
* 修订历史:
* ================================================
*/
public class GankModel implements Serializable {
private static final long serialVersionUID = 6753210234564872868L;
public String _id;
public Date createdAt;
public String desc;
public List images;
public Date publishedAt;
public String source;
public String type;
public String url;
public boolean used;
public String who;
}
================================================
FILE: demo/src/main/java/com/lzy/demo/model/GankResponse.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.model;
import java.io.Serializable;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/29
* 描 述:
* 修订历史:
* ================================================
*/
public class GankResponse implements Serializable {
private static final long serialVersionUID = -686453405647539973L;
public boolean error;
public T results;
}
================================================
FILE: demo/src/main/java/com/lzy/demo/model/ItemModel.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.model;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:2017/6/9
* 描 述:
* 修订历史:
* ================================================
*/
public class ItemModel {
public String title;
public String des;
public int type;
public ItemModel() {
}
public ItemModel(String title, String des) {
this.title = title;
this.des = des;
}
public ItemModel(String title, String des, int type) {
this.title = title;
this.des = des;
this.type = type;
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/model/LzyResponse.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.model;
import java.io.Serializable;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/28
* 描 述:
* 修订历史:
* ================================================
*/
public class LzyResponse implements Serializable {
private static final long serialVersionUID = 5213230387175987834L;
public int code;
public String msg;
public T data;
@Override
public String toString() {
return "LzyResponse{\n" +//
"\tcode=" + code + "\n" +//
"\tmsg='" + msg + "\'\n" +//
"\tdata=" + data + "\n" +//
'}';
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/model/ServerModel.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.model;
import java.io.Serializable;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)
* 版 本:1.0
* 创建日期:2016/4/7
* 描 述:我的Github地址 https://github.com/jeasonlzy
* 修订历史:
* ================================================
*/
public class ServerModel implements Serializable {
private static final long serialVersionUID = -828322761336296999L;
public String method;
public String ip;
public String url;
public String des;
public String upload;
public Author author;
public class Author implements Serializable {
private static final long serialVersionUID = 2701611773813762723L;
public String name;
public String fullname;
public String github;
public String address;
public String qq;
public String email;
public String des;
@Override
public String toString() {
return "Author{\n" +//
"\tname='" + name + "\'\n" +//
"\tfullname='" + fullname + "\'\n" +//
"\tgithub='" + github + "\'\n" +//
"\taddress='" + address + "\'\n" +//
"\tqq='" + qq + "\'\n" +//
"\temail='" + email + "\'\n" +//
"\tdes='" + des + "\'\n" +//
'}';
}
}
@Override
public String toString() {
return "ServerModel{\n" +//
"\tmethod='" + method + "\'\n" +//
"\tip='" + ip + "\'\n" +//
"\turl='" + url + "\'\n" +//
"\tdes='" + des + "\'\n" +//
"\tupload='" + upload + "\'\n" +//
"\tauthor=" + author + "\n" +//
'}';
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/model/SimpleResponse.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.model;
import java.io.Serializable;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/28
* 描 述:
* 修订历史:
* ================================================
*/
public class SimpleResponse implements Serializable {
private static final long serialVersionUID = -1477609349345966116L;
public int code;
public String msg;
public LzyResponse toLzyResponse() {
LzyResponse lzyResponse = new LzyResponse();
lzyResponse.code = code;
lzyResponse.msg = msg;
return lzyResponse;
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/okdownload/DesActivity.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.okdownload;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.format.Formatter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.lzy.demo.R;
import com.lzy.demo.base.BaseActivity;
import com.lzy.demo.model.ApkModel;
import com.lzy.demo.utils.ApkUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import java.io.File;
import java.text.NumberFormat;
import butterknife.Bind;
import butterknife.OnClick;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public class DesActivity extends BaseActivity {
@Bind(R.id.toolbar) Toolbar toolbar;
@Bind(R.id.icon) ImageView icon;
@Bind(R.id.name) TextView name;
@Bind(R.id.downloadSize) TextView downloadSize;
@Bind(R.id.tvProgress) TextView tvProgress;
@Bind(R.id.netSpeed) TextView netSpeed;
@Bind(R.id.pbProgress) ProgressBar pbProgress;
@Bind(R.id.start) Button download;
@Bind(R.id.remove) Button remove;
@Bind(R.id.restart) Button restart;
private NumberFormat numberFormat;
private DownloadTask task;
private ApkModel apk;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_details);
initToolBar(toolbar, true, "下载管理");
apk = (ApkModel) getIntent().getSerializableExtra("apk");
numberFormat = NumberFormat.getPercentInstance();
numberFormat.setMinimumFractionDigits(2);
// 写法一:从内存中获取
if (OkDownload.getInstance().hasTask(apk.url)) {
task = OkDownload.getInstance().getTask(apk.url)//
.register(new DesListener("DesListener"))//
.register(new LogDownloadListener());
}
//写法二:从数据库中恢复
// Progress progress = DownloadManager.getInstance().get(apk.getUrl());
// if (progress != null) {
// task = OkDownload.restore(progress)//
// .register(new DesListener("DesListener"))//
// .register(new LogDownloadListener());
// }
displayImage(apk.iconUrl, icon);
name.setText(apk.name);
if (task != null) refreshUi(task.progress);
}
private void refreshUi(Progress progress) {
String currentSize = Formatter.formatFileSize(this, progress.currentSize);
String totalSize = Formatter.formatFileSize(this, progress.totalSize);
downloadSize.setText(currentSize + "/" + totalSize);
String speed = Formatter.formatFileSize(this, progress.speed);
netSpeed.setText(String.format("%s/s", speed));
tvProgress.setText(numberFormat.format(progress.fraction));
pbProgress.setMax(10000);
pbProgress.setProgress((int) (progress.fraction * 10000));
switch (progress.status) {
case Progress.NONE:
download.setText("下载");
break;
case Progress.LOADING:
download.setText("暂停");
break;
case Progress.PAUSE:
download.setText("继续");
break;
case Progress.WAITING:
download.setText("等待");
break;
case Progress.ERROR:
download.setText("出错");
break;
case Progress.FINISH:
if (ApkUtils.isAvailable(this, new File(progress.filePath))) {
download.setText("卸载");
} else {
download.setText("安装");
}
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (task != null) {
task.unRegister("DesListener");
}
}
@OnClick(R.id.start)
public void start() {
if (task == null) {
//这里只是演示,表示请求可以传参,怎么传都行,和okgo使用方法一样
GetRequest request = OkGo.get(apk.url)//
.headers("aaa", "111")//
.params("bbb", "222");
task = OkDownload.request(apk.url, request)//
.priority(apk.priority)//
.extra1(apk)//
.save()//
.register(new DesListener("DesListener"))//
.register(new LogDownloadListener());
}
switch (task.progress.status) {
case Progress.PAUSE:
case Progress.NONE:
case Progress.ERROR:
task.start();
break;
case Progress.LOADING:
task.pause();
break;
case Progress.FINISH:
File file = new File(task.progress.filePath);
if (ApkUtils.isAvailable(this, file)) {
ApkUtils.uninstall(this, ApkUtils.getPackageName(this, file.getAbsolutePath()));
} else {
ApkUtils.install(this, file);
}
break;
}
}
@OnClick(R.id.remove)
public void remove() {
if (task != null) {
task.remove();
task = null;
}
downloadSize.setText("--M/--M");
netSpeed.setText("---/s");
tvProgress.setText("--.--%");
pbProgress.setProgress(0);
download.setText("下载");
}
@OnClick(R.id.restart)
public void restart() {
if (task != null) task.restart();
}
private class DesListener extends DownloadListener {
DesListener(String tag) {
super(tag);
}
@Override
public void onStart(Progress progress) {
}
@Override
public void onProgress(Progress progress) {
refreshUi(progress);
}
@Override
public void onFinish(File file, Progress progress) {
}
@Override
public void onRemove(Progress progress) {
}
@Override
public void onError(Progress progress) {
Throwable throwable = progress.exception;
if (throwable != null) throwable.printStackTrace();
}
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/okdownload/DownloadAdapter.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.okdownload;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.lzy.demo.R;
import com.lzy.demo.model.ApkModel;
import com.lzy.demo.ui.NumberProgressBar;
import com.lzy.demo.utils.ApkUtils;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import java.io.File;
import java.text.NumberFormat;
import java.util.List;
import java.util.Map;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:2017/6/5
* 描 述:
* 修订历史:
* ================================================
*/
public class DownloadAdapter extends RecyclerView.Adapter {
public static final int TYPE_ALL = 0;
public static final int TYPE_FINISH = 1;
public static final int TYPE_ING = 2;
private List values;
private NumberFormat numberFormat;
private LayoutInflater inflater;
private Context context;
private int type;
public DownloadAdapter(Context context) {
this.context = context;
numberFormat = NumberFormat.getPercentInstance();
numberFormat.setMinimumFractionDigits(2);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void updateData(int type) {
//这里是将数据库的数据恢复
this.type = type;
if (type == TYPE_ALL) values = OkDownload.restore(DownloadManager.getInstance().getAll());
if (type == TYPE_FINISH) values = OkDownload.restore(DownloadManager.getInstance().getFinished());
if (type == TYPE_ING) values = OkDownload.restore(DownloadManager.getInstance().getDownloading());
notifyDataSetChanged();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.item_download_manager, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
DownloadTask task = values.get(position);
String tag = createTag(task);
task.register(new ListDownloadListener(tag, holder))//
.register(new LogDownloadListener());
holder.setTag(tag);
holder.setTask(task);
holder.bind();
holder.refresh(task.progress);
}
public void unRegister() {
Map taskMap = OkDownload.getInstance().getTaskMap();
for (DownloadTask task : taskMap.values()) {
task.unRegister(createTag(task));
}
}
private String createTag(DownloadTask task) {
return type + "_" + task.progress.tag;
}
@Override
public int getItemCount() {
return values == null ? 0 : values.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
@Bind(R.id.icon) ImageView icon;
@Bind(R.id.name) TextView name;
@Bind(R.id.priority) TextView priority;
@Bind(R.id.downloadSize) TextView downloadSize;
@Bind(R.id.tvProgress) TextView tvProgress;
@Bind(R.id.netSpeed) TextView netSpeed;
@Bind(R.id.pbProgress) NumberProgressBar pbProgress;
@Bind(R.id.start) Button download;
private DownloadTask task;
private String tag;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void setTask(DownloadTask task) {
this.task = task;
}
public void bind() {
Progress progress = task.progress;
ApkModel apk = (ApkModel) progress.extra1;
if (apk != null) {
Glide.with(context).load(apk.iconUrl).error(R.mipmap.ic_launcher).into(icon);
name.setText(apk.name);
priority.setText(String.format("优先级:%s", progress.priority));
} else {
name.setText(progress.fileName);
}
}
public void refresh(Progress progress) {
String currentSize = Formatter.formatFileSize(context, progress.currentSize);
String totalSize = Formatter.formatFileSize(context, progress.totalSize);
downloadSize.setText(currentSize + "/" + totalSize);
priority.setText(String.format("优先级:%s", progress.priority));
switch (progress.status) {
case Progress.NONE:
netSpeed.setText("停止");
download.setText("下载");
break;
case Progress.PAUSE:
netSpeed.setText("暂停中");
download.setText("继续");
break;
case Progress.ERROR:
netSpeed.setText("下载出错");
download.setText("出错");
break;
case Progress.WAITING:
netSpeed.setText("等待中");
download.setText("等待");
break;
case Progress.FINISH:
netSpeed.setText("下载完成");
download.setText("完成");
break;
case Progress.LOADING:
String speed = Formatter.formatFileSize(context, progress.speed);
netSpeed.setText(String.format("%s/s", speed));
download.setText("暂停");
break;
}
tvProgress.setText(numberFormat.format(progress.fraction));
pbProgress.setMax(10000);
pbProgress.setProgress((int) (progress.fraction * 10000));
}
@OnClick(R.id.start)
public void start() {
Progress progress = task.progress;
switch (progress.status) {
case Progress.PAUSE:
case Progress.NONE:
case Progress.ERROR:
task.start();
break;
case Progress.LOADING:
task.pause();
break;
case Progress.FINISH:
if (ApkUtils.isAvailable(context, new File(progress.filePath))) {
ApkUtils.uninstall(context, ApkUtils.getPackageName(context, progress.filePath));
} else {
ApkUtils.install(context, new File(progress.filePath));
}
break;
}
refresh(progress);
}
@OnClick(R.id.remove)
public void remove() {
task.remove(true);
updateData(type);
}
@OnClick(R.id.restart)
public void restart() {
task.restart();
}
public void setTag(String tag) {
this.tag = tag;
}
public String getTag() {
return tag;
}
}
private class ListDownloadListener extends DownloadListener {
private ViewHolder holder;
ListDownloadListener(Object tag, ViewHolder holder) {
super(tag);
this.holder = holder;
}
@Override
public void onStart(Progress progress) {
}
@Override
public void onProgress(Progress progress) {
if (tag == holder.getTag()) {
holder.refresh(progress);
}
}
@Override
public void onError(Progress progress) {
Throwable throwable = progress.exception;
if (throwable != null) throwable.printStackTrace();
}
@Override
public void onFinish(File file, Progress progress) {
Toast.makeText(context, "下载完成:" + progress.filePath, Toast.LENGTH_SHORT).show();
updateData(type);
}
@Override
public void onRemove(Progress progress) {
}
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/okdownload/DownloadAllActivity.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.okdownload;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.lzy.demo.R;
import com.lzy.demo.base.BaseActivity;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.task.XExecutor;
import butterknife.Bind;
import butterknife.OnClick;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public class DownloadAllActivity extends BaseActivity implements XExecutor.OnAllTaskEndListener {
@Bind(R.id.toolbar) Toolbar toolbar;
@Bind(R.id.recyclerView) RecyclerView recyclerView;
private DownloadAdapter adapter;
private OkDownload okDownload;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_all);
initToolBar(toolbar, true, "所有任务");
okDownload = OkDownload.getInstance();
adapter = new DownloadAdapter(this);
adapter.updateData(DownloadAdapter.TYPE_ALL);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
okDownload.addOnAllTaskEndListener(this);
}
@Override
public void onAllTaskEnd() {
showToast("所有下载任务已结束");
}
@Override
protected void onDestroy() {
super.onDestroy();
okDownload.removeOnAllTaskEndListener(this);
adapter.unRegister();
}
@Override
protected void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
@OnClick(R.id.removeAll)
public void removeAll(View view) {
okDownload.removeAll();
adapter.updateData(DownloadAdapter.TYPE_ALL);
adapter.notifyDataSetChanged();
}
@OnClick(R.id.pauseAll)
public void pauseAll(View view) {
okDownload.pauseAll();
}
@OnClick(R.id.startAll)
public void startAll(View view) {
okDownload.startAll();
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/okdownload/DownloadFinishActivity.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.okdownload;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import com.lzy.demo.R;
import com.lzy.demo.base.BaseActivity;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.task.XExecutor;
import butterknife.Bind;
import butterknife.OnClick;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public class DownloadFinishActivity extends BaseActivity implements XExecutor.OnAllTaskEndListener {
private DownloadAdapter adapter;
private OkDownload okDownload;
@Bind(R.id.toolbar) Toolbar toolbar;
@Bind(R.id.recyclerView) RecyclerView recyclerView;
@Bind(R.id.pauseAll) Button pauseAll;
@Bind(R.id.startAll) Button startAll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_all);
initToolBar(toolbar, true, "已完成任务");
pauseAll.setVisibility(View.GONE);
startAll.setVisibility(View.GONE);
okDownload = OkDownload.getInstance();
adapter = new DownloadAdapter(this);
adapter.updateData(DownloadAdapter.TYPE_FINISH);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
okDownload.addOnAllTaskEndListener(this);
}
@Override
public void onAllTaskEnd() {
showToast("所有下载任务已结束");
}
@Override
protected void onDestroy() {
super.onDestroy();
okDownload.removeOnAllTaskEndListener(this);
adapter.unRegister();
}
@Override
protected void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
@OnClick(R.id.removeAll)
public void removeAll(View view) {
OkDownload.getInstance().removeAll();
adapter.updateData(DownloadAdapter.TYPE_FINISH);
adapter.notifyDataSetChanged();
}
}
================================================
FILE: demo/src/main/java/com/lzy/demo/okdownload/DownloadListActivity.java
================================================
/*
* Copyright 2016 jeasonlzy(廖子尧)
*
* 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.
*/
package com.lzy.demo.okdownload;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.lzy.demo.R;
import com.lzy.demo.base.BaseActivity;
import com.lzy.demo.base.BaseRecyclerAdapter;
import com.lzy.demo.base.DividerItemDecoration;
import com.lzy.demo.model.ApkModel;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public class DownloadListActivity extends BaseActivity {
private static final int REQUEST_PERMISSION_STORAGE = 0x01;
@Bind(R.id.toolbar) Toolbar toolbar;
@Bind(R.id.targetFolder) TextView folder;
@Bind(R.id.recyclerView) RecyclerView recyclerView;
private List apks;
private DownloadListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_list);
initToolBar(toolbar, true, "开始下载");
initData();
OkDownload.getInstance().setFolder(Environment.getExternalStorageDirectory().getAbsolutePath() + "/aaa/");
OkDownload.getInstance().getThreadPool().setCorePoolSize(3);
folder.setText(String.format("下载路径: %s", OkDownload.getInstance().getFolder()));
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
//从数据库中恢复数据
List