├── .gitignore
├── .idea
├── .name
├── compiler.xml
├── copyright
│ └── profiles_settings.xml
├── encodings.xml
├── gradle.xml
├── misc.xml
├── modules.xml
├── runConfigurations.xml
└── vcs.xml
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── example
│ │ └── ljd
│ │ └── retrofit
│ │ └── ApplicationTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── example
│ │ │ └── ljd
│ │ │ └── retrofit
│ │ │ ├── GithubApi.java
│ │ │ ├── GithubService.java
│ │ │ ├── MainActivity.java
│ │ │ ├── RxUtils.java
│ │ │ ├── download
│ │ │ ├── DownloadActivity.java
│ │ │ └── DownloadApi.java
│ │ │ └── pojo
│ │ │ ├── Contributor.java
│ │ │ ├── Example.java
│ │ │ ├── Item.java
│ │ │ ├── Owner.java
│ │ │ ├── RetrofitBean.java
│ │ │ └── User.java
│ └── res
│ │ ├── layout
│ │ ├── activity_download.xml
│ │ └── activity_main.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── example
│ └── ljd
│ └── retrofit
│ └── exampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── ljd
│ │ └── retrofit
│ │ └── progress
│ │ ├── DownloadProgressHandler.java
│ │ ├── ProgressBean.java
│ │ ├── ProgressHandler.java
│ │ ├── ProgressHelper.java
│ │ ├── ProgressListener.java
│ │ ├── ProgressRequestBody.java
│ │ ├── ProgressResponseBody.java
│ │ └── UploadProgressHandler.java
│ └── res
│ └── values
│ └── strings.xml
├── libs
└── android-async-http-1.4.9.jar
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 |
--------------------------------------------------------------------------------
/.idea/.name:
--------------------------------------------------------------------------------
1 | retrofit-example
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
24 |
25 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # retrofit-example
2 | retrofit基本用法:http://blog.csdn.net/ljd2038/article/details/51046512
3 |
4 | 解决retrofit文件下载的进度显示问题:http://blog.csdn.net/ljd2038/article/details/51189334
5 |
6 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | applicationId "com.Example.ljd.retrofit"
9 | minSdkVersion 15
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | testCompile 'junit:junit:4.12'
25 | compile 'com.android.support:support-v4:23.2.0'
26 | compile 'com.android.support:appcompat-v7:23.2.0'
27 | compile 'com.jakewharton:butterknife:7.0.1'
28 | compile 'com.squareup.retrofit2:retrofit:2.0.1'
29 | compile 'com.squareup.retrofit2:converter-gson:2.0.1'
30 | compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'
31 | compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'
32 | compile 'io.reactivex:rxandroid:1.1.0'
33 | compile project(":library")
34 | }
35 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/ljd/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/example/ljd/retrofit/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.example.ljd.retrofit;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/ljd/retrofit/GithubApi.java:
--------------------------------------------------------------------------------
1 | package com.example.ljd.retrofit;
2 |
3 | import com.example.ljd.retrofit.pojo.Contributor;
4 | import com.example.ljd.retrofit.pojo.RetrofitBean;
5 | import com.example.ljd.retrofit.pojo.User;
6 |
7 | import java.util.List;
8 | import java.util.Map;
9 |
10 | import okhttp3.ResponseBody;
11 | import retrofit2.Call;
12 | import retrofit2.http.GET;
13 | import retrofit2.http.Headers;
14 | import retrofit2.http.Path;
15 | import retrofit2.http.Query;
16 | import retrofit2.http.QueryMap;
17 | import rx.Observable;
18 |
19 | /**
20 | * Created by ljd on 3/25/16.
21 | */
22 | public interface GitHubApi {
23 |
24 | @GET("repos/{owner}/{repo}/contributors")
25 | Call contributorsBySimpleGetCall(@Path("owner") String owner, @Path("repo") String repo);
26 |
27 | @GET("repos/{owner}/{repo}/contributors")
28 | Call> contributorsByAddConverterGetCall(@Path("owner") String owner, @Path("repo") String repo);
29 |
30 | @Headers({
31 | "Accept: application/vnd.github.v3.full+json",
32 | "User-Agent: RetrofitBean-Sample-App",
33 | "name:ljd"
34 | })
35 | @GET("repos/{owner}/{repo}/contributors")
36 | Call> contributorsAndAddHeader(@Path("owner") String owner, @Path("repo") String repo);
37 |
38 | @GET("search/repositories")
39 | Call queryRetrofitByGetCall(@Query("q")String owner,
40 | @Query("since")String time,
41 | @Query("page")int page,
42 | @Query("per_page")int per_Page);
43 |
44 | @GET("search/repositories")
45 | Call queryRetrofitByGetCallMap(@QueryMap Map map);
46 |
47 |
48 |
49 | @GET("repos/{owner}/{repo}/contributors")
50 | Observable> contributorsByRxJava(@Path("owner") String owner,
51 | @Path("repo") String repo);
52 |
53 | @GET("users/{user}")
54 | Observable userByRxJava(@Path("user") String user);
55 |
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/ljd/retrofit/GithubService.java:
--------------------------------------------------------------------------------
1 | package com.example.ljd.retrofit;
2 |
3 |
4 | import com.ljd.retrofit.progress.ProgressHelper;
5 |
6 | import okhttp3.OkHttpClient;
7 | import okhttp3.logging.HttpLoggingInterceptor;
8 | import retrofit2.Retrofit;
9 | import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
10 | import retrofit2.converter.gson.GsonConverterFactory;
11 |
12 |
13 | /**
14 | * Created by ljd on 3/25/16.
15 | */
16 | public class GitHubService {
17 |
18 | private GitHubService() { }
19 |
20 | public static T createRetrofitService(final Class service) {
21 | HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
22 | httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
23 | OkHttpClient.Builder builder = new OkHttpClient.Builder()
24 | .addInterceptor(httpLoggingInterceptor);
25 |
26 | Retrofit retrofit = new Retrofit.Builder()
27 | .client(ProgressHelper.addProgress(builder).build())
28 | .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
29 | .addConverterFactory(GsonConverterFactory.create())
30 | .baseUrl("https://api.github.com/")
31 | .build();
32 |
33 | return retrofit.create(service);
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/ljd/retrofit/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.example.ljd.retrofit;
2 |
3 | import android.content.Intent;
4 | import android.support.v4.app.FragmentActivity;
5 | import android.os.Bundle;
6 | import android.util.Log;
7 | import android.util.Pair;
8 | import android.view.View;
9 |
10 | import com.example.ljd.retrofit.download.DownloadActivity;
11 | import com.example.ljd.retrofit.pojo.Contributor;
12 | import com.example.ljd.retrofit.pojo.Item;
13 | import com.example.ljd.retrofit.pojo.Owner;
14 | import com.example.ljd.retrofit.pojo.RetrofitBean;
15 | import com.example.ljd.retrofit.pojo.User;
16 | import com.google.gson.Gson;
17 | import com.google.gson.reflect.TypeToken;
18 |
19 | import java.io.IOException;
20 | import java.util.ArrayList;
21 | import java.util.HashMap;
22 | import java.util.List;
23 | import java.util.Map;
24 |
25 | import butterknife.ButterKnife;
26 | import butterknife.OnClick;
27 | import okhttp3.OkHttpClient;
28 | import okhttp3.ResponseBody;
29 | import okhttp3.logging.HttpLoggingInterceptor;
30 | import retrofit2.Call;
31 | import retrofit2.Callback;
32 | import retrofit2.Response;
33 | import retrofit2.Retrofit;
34 | import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
35 | import retrofit2.converter.gson.GsonConverterFactory;
36 | import rx.Observable;
37 | import rx.Observer;
38 | import rx.android.schedulers.AndroidSchedulers;
39 | import rx.functions.Func1;
40 | import rx.functions.Func2;
41 | import rx.schedulers.Schedulers;
42 | import rx.subscriptions.CompositeSubscription;
43 |
44 | import static android.text.TextUtils.isEmpty;
45 |
46 |
47 | public class MainActivity extends FragmentActivity{
48 |
49 | private GitHubApi mGitHubService;
50 | private String mUserName;
51 | private String mRepo;
52 | private CompositeSubscription mSubscriptions = new CompositeSubscription();
53 | private final static String TAG = "MainActivity";
54 |
55 | @Override
56 | public void onBackPressed() {
57 | super.onBackPressed();
58 | }
59 |
60 | @Override
61 | protected void onCreate(Bundle savedInstanceState) {
62 | super.onCreate(savedInstanceState);
63 | setContentView(R.layout.activity_main);
64 | initData();
65 | }
66 |
67 | @Override
68 | protected void onDestroy() {
69 | RxUtils.unSubscribeIfNotNull(mSubscriptions);
70 | ButterKnife.unbind(this);
71 | super.onDestroy();
72 | }
73 |
74 | private void initData(){
75 | ButterKnife.bind(this);
76 | mGitHubService = GitHubService.createRetrofitService(GitHubApi.class);
77 | mSubscriptions = RxUtils.getNewCompositeSubIfUnsubscribed(mSubscriptions);
78 | mUserName = getResources().getString(R.string.user_name);
79 | mRepo = getResources().getString(R.string.repo);
80 | }
81 |
82 | @OnClick({R.id.btn_retrofit_simple_contributors,
83 | R.id.btn_retrofit_converter_contributors,
84 | R.id.btn_retrofit_sync_contributors,
85 | R.id.btn_add_okhttp_log_contributors,
86 | R.id.btn_add_header_contributors,
87 | R.id.btn_retrofit_get_query,
88 | R.id.btn_retrofit_get_query_map,
89 | R.id.btn_rxJava_retrofit_contributors,
90 | R.id.btn_rxJava_retrofit_contributors_with_user_info,
91 | R.id.btn_download_retrofit,
92 | })
93 | public void onClickButton(View v){
94 | Map queryMap = new HashMap<>();
95 | queryMap.put("q", "retrofit");
96 | queryMap.put("since","2016-03-29");
97 | queryMap.put("page","1");
98 | queryMap.put("per_page", "3");
99 | switch (v.getId()){
100 | //简单演示retrofit的使用
101 | case R.id.btn_retrofit_simple_contributors:
102 | requestGitHubContributorsSimple();
103 | break;
104 | //添加转换器
105 | case R.id.btn_retrofit_converter_contributors:
106 | requestGitHubContributorsByConverter();
107 | break;
108 | //添加okHttp的Log信息
109 | case R.id.btn_add_okhttp_log_contributors:
110 | requestGitHubContributorsAddOkHttpLog();
111 | break;
112 | //添加请求头
113 | case R.id.btn_add_header_contributors:
114 | requestGitHubContributorsAddHeader();
115 | break;
116 | //同步请求
117 | case R.id.btn_retrofit_sync_contributors:
118 | requestGitHubContributorsBySync();
119 | break;
120 | //通过get请求,使用@Query
121 | case R.id.btn_retrofit_get_query:
122 | requestQueryRetrofitByGet(null);
123 | break;
124 | //通过get请求,使用@QueryMap
125 | case R.id.btn_retrofit_get_query_map:
126 | requestQueryRetrofitByGet(queryMap);
127 | break;
128 | //rxJava+retrofit
129 | case R.id.btn_rxJava_retrofit_contributors:
130 | requestGitHubContributorsByRxJava();
131 | break;
132 | //rxJava+retrofit
133 | case R.id.btn_rxJava_retrofit_contributors_with_user_info:
134 | requestGitHubContributorsWithFullUserInfo();
135 | break;
136 | //文件下载
137 | case R.id.btn_download_retrofit:
138 | Intent intent = new Intent(this, DownloadActivity.class);
139 | startActivity(intent);
140 | break;
141 |
142 | }
143 | }
144 |
145 | /**
146 | * 简单示例
147 | */
148 | private void requestGitHubContributorsSimple(){
149 |
150 | Retrofit retrofit = new Retrofit.Builder()
151 | .baseUrl("https://api.github.com/")
152 | .build();
153 | GitHubApi repo = retrofit.create(GitHubApi.class);
154 |
155 | Call call = repo.contributorsBySimpleGetCall(mUserName, mRepo);
156 | call.enqueue(new Callback() {
157 | @Override
158 | public void onResponse(Call call, Response response) {
159 | try {
160 | Gson gson = new Gson();
161 | ArrayList contributorsList = gson.fromJson(response.body().string(), new TypeToken>() {
162 | }.getType());
163 | for (Contributor contributor : contributorsList) {
164 | Log.d("login", contributor.getLogin());
165 | Log.d("contributions", contributor.getContributions() + "");
166 | }
167 | } catch (IOException e) {
168 | e.printStackTrace();
169 | }
170 | }
171 |
172 | @Override
173 | public void onFailure(Call call, Throwable t) {
174 |
175 | }
176 | });
177 | }
178 |
179 | /**
180 | * 转换器
181 | */
182 | private void requestGitHubContributorsByConverter(){
183 | Retrofit retrofit = new Retrofit.Builder()
184 | .baseUrl("https://api.github.com/")
185 | .addConverterFactory(GsonConverterFactory.create())
186 | .build();
187 |
188 | GitHubApi repo = retrofit.create(GitHubApi.class);
189 | Call> call = repo.contributorsByAddConverterGetCall(mUserName, mRepo);
190 | call.enqueue(new Callback>() {
191 | @Override
192 | public void onResponse(Call> call, Response> response) {
193 | List contributorList = response.body();
194 | for (Contributor contributor : contributorList){
195 | Log.d("login", contributor.getLogin());
196 | Log.d("contributions", contributor.getContributions() + "");
197 | }
198 | }
199 |
200 | @Override
201 | public void onFailure(Call> call, Throwable t) {
202 |
203 | }
204 | });
205 | }
206 |
207 | /**
208 | * 添加日志信息
209 | */
210 | private void requestGitHubContributorsAddOkHttpLog(){
211 |
212 | HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
213 | httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
214 | OkHttpClient okHttpClient = new OkHttpClient.Builder()
215 | .addInterceptor(httpLoggingInterceptor)
216 | .build();
217 |
218 | Retrofit retrofit = new Retrofit.Builder().addCallAdapterFactory(RxJavaCallAdapterFactory.create())
219 | .client(okHttpClient)
220 | .baseUrl("https://api.github.com/")
221 | .addConverterFactory(GsonConverterFactory.create())
222 | .build();
223 |
224 | GitHubApi repo = retrofit.create(GitHubApi.class);
225 |
226 | Call> call = repo.contributorsByAddConverterGetCall(mUserName, mRepo);
227 | call.enqueue(new Callback>() {
228 | @Override
229 | public void onResponse(Call> call, Response> response) {
230 | List contributorList = response.body();
231 | for (Contributor contributor : contributorList){
232 | Log.d("login", contributor.getLogin());
233 | Log.d("contributions", contributor.getContributions() + "");
234 | }
235 | }
236 |
237 | @Override
238 | public void onFailure(Call> call, Throwable t) {
239 |
240 | }
241 | });
242 | }
243 |
244 | /**
245 | * 添加请求头
246 | */
247 | private void requestGitHubContributorsAddHeader(){
248 |
249 | Call> call = mGitHubService.contributorsAndAddHeader(mUserName, mRepo);
250 | call.enqueue(new Callback>() {
251 | @Override
252 | public void onResponse(Call> call, Response> response) {
253 | List contributorList = response.body();
254 | for (Contributor contributor : contributorList) {
255 | Log.d("login", contributor.getLogin());
256 | Log.d("contributions", contributor.getContributions() + "");
257 | }
258 | }
259 |
260 | @Override
261 | public void onFailure(Call> call, Throwable t) {
262 |
263 | }
264 | });
265 | }
266 |
267 | /**
268 | * 同步请求
269 | */
270 | private void requestGitHubContributorsBySync(){
271 |
272 | final Call> call = mGitHubService.contributorsByAddConverterGetCall(mUserName, mRepo);
273 | new Thread(new Runnable() {
274 | @Override
275 | public void run() {
276 |
277 | try {
278 | Response> response = call.execute();
279 |
280 | List contributorsList = response.body();
281 | for (Contributor contributor : contributorsList){
282 | Log.d("login",contributor.getLogin());
283 | Log.d("contributions",contributor.getContributions()+"");
284 | }
285 | } catch (IOException e) {
286 | e.printStackTrace();
287 | }
288 | }
289 | }).start();
290 | }
291 |
292 | /**
293 | * get请求
294 | * @param queryMap
295 | */
296 | private void requestQueryRetrofitByGet(Map queryMap){
297 | Call call;
298 | if (queryMap == null || queryMap.size() == 0){
299 | call = mGitHubService.queryRetrofitByGetCall("retrofit", "2016-03-29", 1, 3);
300 | } else {
301 | call = mGitHubService.queryRetrofitByGetCallMap(queryMap);
302 | }
303 |
304 | call.enqueue(new Callback() {
305 | @Override
306 | public void onResponse(Call call, Response response) {
307 | RetrofitBean retrofit = response.body();
308 | List- list = retrofit.getItems();
309 | if (list == null)
310 | return;
311 | Log.d(TAG, "total:" + retrofit.getTotalCount());
312 | Log.d(TAG, "incompleteResults:" + retrofit.getIncompleteResults());
313 | Log.d(TAG, "----------------------");
314 | for (Item item : list) {
315 | Log.d(TAG, "name:" + item.getName());
316 | Log.d(TAG, "full_name:" + item.getFull_name());
317 | Log.d(TAG, "description:" + item.getDescription());
318 | Owner owner = item.getOwner();
319 | Log.d(TAG, "login:" + owner.getLogin());
320 | Log.d(TAG, "type:" + owner.getType());
321 | }
322 |
323 | }
324 |
325 | @Override
326 | public void onFailure(Call call, Throwable t) {
327 |
328 | }
329 | });
330 | }
331 |
332 | /**
333 | * retrofit+rxJava
334 | */
335 | private void requestGitHubContributorsByRxJava(){
336 |
337 | mSubscriptions.add(
338 | mGitHubService.contributorsByRxJava(mUserName, mRepo)
339 | .subscribeOn(Schedulers.io())
340 | .observeOn(AndroidSchedulers.mainThread())
341 | .subscribe(new Observer
>() {
342 | @Override
343 | public void onCompleted() {
344 | }
345 |
346 | @Override
347 | public void onError(Throwable e) {
348 | }
349 |
350 | @Override
351 | public void onNext(List contributors) {
352 | for (Contributor c : contributors) {
353 | Log.d("TAG", "login:" + c.getLogin() + " contributions:" + c.getContributions());
354 | }
355 | }
356 | }));
357 | }
358 |
359 | /**
360 | * retrofit+rxJava
361 | */
362 | private void requestGitHubContributorsWithFullUserInfo(){
363 | mSubscriptions.add(mGitHubService.contributorsByRxJava(mUserName, mRepo)
364 | .flatMap(new Func1, Observable>() {
365 | @Override
366 | public Observable call(List contributors) {
367 | return Observable.from(contributors);
368 | }
369 | })
370 | .flatMap(new Func1>>() {
371 | @Override
372 | public Observable> call(Contributor contributor) {
373 | Observable userObservable = mGitHubService.userByRxJava(contributor.getLogin())
374 | .filter(new Func1() {
375 | @Override
376 | public Boolean call(User user) {
377 | return !isEmpty(user.getName()) && !isEmpty(user.getEmail());
378 | }
379 | });
380 |
381 | return Observable.zip(userObservable,
382 | Observable.just(contributor),
383 | new Func2>() {
384 | @Override
385 | public Pair call(User user, Contributor contributor) {
386 | return new Pair<>(user, contributor);
387 | }
388 | });
389 | }
390 | })
391 | .subscribeOn(Schedulers.newThread())
392 | .observeOn(AndroidSchedulers.mainThread())
393 | .subscribe(new Observer>() {
394 | @Override
395 | public void onCompleted() {
396 |
397 | }
398 |
399 | @Override
400 | public void onError(Throwable e) {
401 |
402 | }
403 |
404 | @Override
405 | public void onNext(Pair pair) {
406 | User user = pair.first;
407 | Contributor contributor = pair.second;
408 | Log.d(TAG, "name:" + user.getName());
409 | Log.d(TAG, "contributions:" + contributor.getContributions());
410 | Log.d(TAG, "email:" + user.getEmail());
411 |
412 | }
413 | }));
414 | }
415 |
416 | }
417 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/ljd/retrofit/RxUtils.java:
--------------------------------------------------------------------------------
1 | package com.example.ljd.retrofit;
2 |
3 | import rx.Subscription;
4 | import rx.subscriptions.CompositeSubscription;
5 |
6 | public class RxUtils {
7 |
8 | public static void unSubscribeIfNotNull(Subscription subscription) {
9 | if (subscription != null) {
10 | subscription.unsubscribe();
11 | }
12 | }
13 |
14 | public static CompositeSubscription getNewCompositeSubIfUnsubscribed(CompositeSubscription subscription) {
15 | if (subscription == null || subscription.isUnsubscribed()) {
16 | return new CompositeSubscription();
17 | }
18 |
19 | return subscription;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/ljd/retrofit/download/DownloadActivity.java:
--------------------------------------------------------------------------------
1 |
2 | package com.example.ljd.retrofit.download;
3 |
4 | import android.app.ProgressDialog;
5 | import android.os.Environment;
6 | import android.os.Looper;
7 | import android.support.v7.app.AppCompatActivity;
8 | import android.os.Bundle;
9 | import android.util.Log;
10 |
11 | import com.example.ljd.retrofit.R;
12 | import com.ljd.retrofit.progress.DownloadProgressHandler;
13 | import com.ljd.retrofit.progress.ProgressHelper;
14 |
15 |
16 | import java.io.BufferedInputStream;
17 | import java.io.File;
18 | import java.io.FileOutputStream;
19 | import java.io.IOException;
20 | import java.io.InputStream;
21 |
22 | import butterknife.ButterKnife;
23 | import butterknife.OnClick;
24 | import okhttp3.OkHttpClient;
25 | import okhttp3.ResponseBody;
26 | import retrofit2.Call;
27 | import retrofit2.Callback;
28 | import retrofit2.Response;
29 | import retrofit2.Retrofit;
30 | import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
31 | import retrofit2.converter.gson.GsonConverterFactory;
32 |
33 | public class DownloadActivity extends AppCompatActivity {
34 |
35 |
36 | @Override
37 | protected void onCreate(Bundle savedInstanceState) {
38 | super.onCreate(savedInstanceState);
39 | setContentView(R.layout.activity_download);
40 | ButterKnife.bind(this);
41 |
42 | }
43 |
44 | @Override
45 | protected void onDestroy() {
46 | ButterKnife.unbind(this);
47 | super.onDestroy();
48 | }
49 |
50 | @OnClick(R.id.start_download_btn)
51 | public void onClickButton(){
52 | retrofitDownload();
53 | }
54 |
55 | private void retrofitDownload(){
56 | //监听下载进度
57 | final ProgressDialog dialog = new ProgressDialog(this);
58 | dialog.setProgressNumberFormat("%1d KB/%2d KB");
59 | dialog.setTitle("下载");
60 | dialog.setMessage("正在下载,请稍后...");
61 | dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
62 | dialog.setCancelable(false);
63 | dialog.show();
64 |
65 | Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
66 | .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
67 | .addConverterFactory(GsonConverterFactory.create())
68 | .baseUrl("http://msoftdl.360.cn");
69 | OkHttpClient.Builder builder = ProgressHelper.addProgress(null);
70 | DownloadApi retrofit = retrofitBuilder
71 | .client(builder.build())
72 | .build().create(DownloadApi.class);
73 |
74 | ProgressHelper.setProgressHandler(new DownloadProgressHandler() {
75 | @Override
76 | protected void onProgress(long bytesRead, long contentLength, boolean done) {
77 | Log.e("是否在主线程中运行", String.valueOf(Looper.getMainLooper() == Looper.myLooper()));
78 | Log.e("onProgress",String.format("%d%% done\n",(100 * bytesRead) / contentLength));
79 | Log.e("done","--->" + String.valueOf(done));
80 | dialog.setMax((int) (contentLength/1024));
81 | dialog.setProgress((int) (bytesRead/1024));
82 |
83 | if(done){
84 | dialog.dismiss();
85 | }
86 | }
87 | });
88 |
89 | Call call = retrofit.retrofitDownload();
90 | call.enqueue(new Callback() {
91 | @Override
92 | public void onResponse(Call call, Response response) {
93 | try {
94 | InputStream is = response.body().byteStream();
95 | File file = new File(Environment.getExternalStorageDirectory(), "12345.apk");
96 | FileOutputStream fos = new FileOutputStream(file);
97 | BufferedInputStream bis = new BufferedInputStream(is);
98 | byte[] buffer = new byte[1024];
99 | int len;
100 | while ((len = bis.read(buffer)) != -1) {
101 | fos.write(buffer, 0, len);
102 | fos.flush();
103 | }
104 | fos.close();
105 | bis.close();
106 | is.close();
107 | } catch (IOException e) {
108 | e.printStackTrace();
109 | }
110 | }
111 |
112 | @Override
113 | public void onFailure(Call call, Throwable t) {
114 |
115 | }
116 | });
117 |
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/ljd/retrofit/download/DownloadApi.java:
--------------------------------------------------------------------------------
1 | package com.example.ljd.retrofit.download;
2 |
3 | import okhttp3.ResponseBody;
4 | import retrofit2.Call;
5 | import retrofit2.http.GET;
6 |
7 | /**
8 | * Created by ljd on 3/29/16.
9 | */
10 | public interface DownloadApi {
11 |
12 | @GET("/mobilesafe/shouji360/360safesis/360MobileSafe_6.2.3.1060.apk")
13 | Call retrofitDownload();
14 | }
15 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/ljd/retrofit/pojo/Contributor.java:
--------------------------------------------------------------------------------
1 | package com.example.ljd.retrofit.pojo;
2 |
3 |
4 | /**
5 | * Created by ljd on 3/25/16.
6 | */
7 | public class Contributor {
8 | private String login;
9 | private Integer contributions;
10 |
11 | public String getLogin() {
12 | return login;
13 | }
14 |
15 | public void setLogin(String login) {
16 | this.login = login;
17 | }
18 |
19 | public Integer getContributions() {
20 | return contributions;
21 | }
22 |
23 | public void setContributions(Integer contributions) {
24 | this.contributions = contributions;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/ljd/retrofit/pojo/Example.java:
--------------------------------------------------------------------------------
1 | package com.example.ljd.retrofit.pojo;
2 |
3 | /**
4 | * Created by ljd on 4/2/16.
5 | */
6 | public class Example {
7 |
8 |
9 | /**
10 | * type : object
11 | * properties : {"foo":{"type":"string"},"bar":{"type":"integer"},"baz":{"type":"boolean"}}
12 | */
13 |
14 | private String type;
15 | /**
16 | * foo : {"type":"string"}
17 | * bar : {"type":"integer"}
18 | * baz : {"type":"boolean"}
19 | */
20 |
21 | private PropertiesBean properties;
22 |
23 | public String getType() {
24 | return type;
25 | }
26 |
27 | public void setType(String type) {
28 | this.type = type;
29 | }
30 |
31 | public PropertiesBean getProperties() {
32 | return properties;
33 | }
34 |
35 | public void setProperties(PropertiesBean properties) {
36 | this.properties = properties;
37 | }
38 |
39 | public static class PropertiesBean {
40 | /**
41 | * type : string
42 | */
43 |
44 | private FooBean foo;
45 | /**
46 | * type : integer
47 | */
48 |
49 | private BarBean bar;
50 | /**
51 | * type : boolean
52 | */
53 |
54 | private BazBean baz;
55 |
56 | public FooBean getFoo() {
57 | return foo;
58 | }
59 |
60 | public void setFoo(FooBean foo) {
61 | this.foo = foo;
62 | }
63 |
64 | public BarBean getBar() {
65 | return bar;
66 | }
67 |
68 | public void setBar(BarBean bar) {
69 | this.bar = bar;
70 | }
71 |
72 | public BazBean getBaz() {
73 | return baz;
74 | }
75 |
76 | public void setBaz(BazBean baz) {
77 | this.baz = baz;
78 | }
79 |
80 | public static class FooBean {
81 | private String type;
82 |
83 | public String getType() {
84 | return type;
85 | }
86 |
87 | public void setType(String type) {
88 | this.type = type;
89 | }
90 | }
91 |
92 | public static class BarBean {
93 | private String type;
94 |
95 | public String getType() {
96 | return type;
97 | }
98 |
99 | public void setType(String type) {
100 | this.type = type;
101 | }
102 | }
103 |
104 | public static class BazBean {
105 | private String type;
106 |
107 | public String getType() {
108 | return type;
109 | }
110 |
111 | public void setType(String type) {
112 | this.type = type;
113 | }
114 | }
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/ljd/retrofit/pojo/Item.java:
--------------------------------------------------------------------------------
1 | package com.example.ljd.retrofit.pojo;
2 |
3 |
4 | /**
5 | * Created by ljd on 3/29/16.
6 | */
7 |
8 | public class Item {
9 |
10 | private String name;
11 | private String full_name;
12 | private String description;
13 | private Owner owner;
14 |
15 | public String getName() {
16 | return name;
17 | }
18 |
19 | public void setName(String name) {
20 | this.name = name;
21 | }
22 |
23 | public String getFull_name() {
24 | return full_name;
25 | }
26 |
27 | public void setFull_name(String full_name) {
28 | this.full_name = full_name;
29 | }
30 |
31 | public String getDescription() {
32 | return description;
33 | }
34 |
35 | public void setDescription(String description) {
36 | this.description = description;
37 | }
38 |
39 | public Owner getOwner() {
40 | return owner;
41 | }
42 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/ljd/retrofit/pojo/Owner.java:
--------------------------------------------------------------------------------
1 | package com.example.ljd.retrofit.pojo;
2 |
3 |
4 | /**
5 | * Created by ljd on 3/29/16.
6 | */
7 | public class Owner {
8 |
9 | private String login;
10 | private String type;
11 |
12 | public String getLogin() {
13 | return login;
14 | }
15 |
16 | public void setLogin(String login) {
17 | this.login = login;
18 | }
19 |
20 | public String getType() {
21 | return type;
22 | }
23 |
24 | public void setType(String type) {
25 | this.type = type;
26 | }
27 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/example/ljd/retrofit/pojo/RetrofitBean.java:
--------------------------------------------------------------------------------
1 | package com.example.ljd.retrofit.pojo;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by ljd on 3/29/16.
8 | */
9 | public class RetrofitBean {
10 |
11 | private Integer total_count;
12 | private Boolean incompleteResults;
13 | private List- items = new ArrayList
- ();
14 |
15 | /**
16 | *
17 | * @return
18 | * The totalCount
19 | */
20 | public Integer getTotalCount() {
21 | return total_count;
22 | }
23 |
24 | /**
25 | *
26 | * @param totalCount
27 | * The total_count
28 | */
29 | public void setTotalCount(Integer totalCount) {
30 | this.total_count = totalCount;
31 | }
32 |
33 | /**
34 | *
35 | * @return
36 | * The incompleteResults
37 | */
38 | public Boolean getIncompleteResults() {
39 | return incompleteResults;
40 | }
41 |
42 | /**
43 | *
44 | * @param incompleteResults
45 | * The incomplete_results
46 | */
47 | public void setIncompleteResults(Boolean incompleteResults) {
48 | this.incompleteResults = incompleteResults;
49 | }
50 |
51 | /**
52 | *
53 | * @return
54 | * The items
55 | */
56 | public List
- getItems() {
57 | return items;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/ljd/retrofit/pojo/User.java:
--------------------------------------------------------------------------------
1 | package com.example.ljd.retrofit.pojo;
2 |
3 |
4 | public class User {
5 |
6 | private String name;
7 | private String email;
8 |
9 | public String getName() {
10 | return name;
11 | }
12 |
13 | public void setLogin(String login) {
14 | this.name = login;
15 | }
16 |
17 | public String getEmail() {
18 | return email;
19 | }
20 |
21 | public void setEmail(String email) {
22 | this.email = email;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_download.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
14 |
15 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
16 |
22 |
23 |
29 |
35 |
36 |
42 |
43 |
47 |
48 |
55 |
56 |
63 |
64 |
65 |
69 |
77 |
85 |
86 |
87 |
94 |
95 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lijiangdong/retrofit-example/51d84874fb40146b1b842e0ae56b70d9e46ddc9d/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lijiangdong/retrofit-example/51d84874fb40146b1b842e0ae56b70d9e46ddc9d/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lijiangdong/retrofit-example/51d84874fb40146b1b842e0ae56b70d9e46ddc9d/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lijiangdong/retrofit-example/51d84874fb40146b1b842e0ae56b70d9e46ddc9d/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lijiangdong/retrofit-example/51d84874fb40146b1b842e0ae56b70d9e46ddc9d/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | retrofit-example
3 | 9d43774b1ce07bc1abb84310252bc87b2f036a50
4 | 清空
5 | square
6 | retrofit
7 |
8 | Hello blank fragment
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/example/ljd/retrofit/exampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.example.ljd.retrofit;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class exampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.0.0'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lijiangdong/retrofit-example/51d84874fb40146b1b842e0ae56b70d9e46ddc9d/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.3"
6 |
7 | defaultConfig {
8 | minSdkVersion 9
9 | targetSdkVersion 23
10 | versionCode 1
11 | versionName "1.0"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | compile fileTree(dir: 'libs', include: ['*.jar'])
23 | testCompile 'junit:junit:4.12'
24 | compile 'com.android.support:appcompat-v7:23.3.0'
25 | compile 'com.squareup.retrofit2:retrofit:2.0.1'
26 | }
27 |
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/ljd/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/library/src/main/java/com/ljd/retrofit/progress/DownloadProgressHandler.java:
--------------------------------------------------------------------------------
1 | package com.ljd.retrofit.progress;
2 |
3 |
4 | import android.os.Looper;
5 | import android.os.Message;
6 |
7 | /**
8 | * Created by ljd on 4/12/16.
9 | */
10 | public abstract class DownloadProgressHandler extends ProgressHandler{
11 |
12 | private static final int DOWNLOAD_PROGRESS = 1;
13 | protected ResponseHandler mHandler = new ResponseHandler(this, Looper.getMainLooper());
14 |
15 | @Override
16 | protected void sendMessage(ProgressBean progressBean) {
17 | mHandler.obtainMessage(DOWNLOAD_PROGRESS,progressBean).sendToTarget();
18 |
19 | }
20 |
21 | @Override
22 | protected void handleMessage(Message message){
23 | switch (message.what){
24 | case DOWNLOAD_PROGRESS:
25 | ProgressBean progressBean = (ProgressBean)message.obj;
26 | onProgress(progressBean.getBytesRead(),progressBean.getContentLength(),progressBean.isDone());
27 |
28 | }
29 | }
30 |
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/library/src/main/java/com/ljd/retrofit/progress/ProgressBean.java:
--------------------------------------------------------------------------------
1 | package com.ljd.retrofit.progress;
2 |
3 | /**
4 | * Created by ljd on 4/12/16.
5 | */
6 | public class ProgressBean {
7 |
8 | private long bytesRead;
9 | private long contentLength;
10 | private boolean done;
11 |
12 | public long getBytesRead() {
13 | return bytesRead;
14 | }
15 |
16 | public void setBytesRead(long bytesRead) {
17 | this.bytesRead = bytesRead;
18 | }
19 |
20 | public long getContentLength() {
21 | return contentLength;
22 | }
23 |
24 | public void setContentLength(long contentLength) {
25 | this.contentLength = contentLength;
26 | }
27 |
28 | public boolean isDone() {
29 | return done;
30 | }
31 |
32 | public void setDone(boolean done) {
33 | this.done = done;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/library/src/main/java/com/ljd/retrofit/progress/ProgressHandler.java:
--------------------------------------------------------------------------------
1 | package com.ljd.retrofit.progress;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 | import android.os.Message;
6 |
7 | /**
8 | * Created by ljd on 4/12/16.
9 | */
10 | public abstract class ProgressHandler {
11 |
12 | protected abstract void sendMessage(ProgressBean progressBean);
13 |
14 | protected abstract void handleMessage(Message message);
15 |
16 | protected abstract void onProgress(long progress, long total, boolean done);
17 |
18 | protected static class ResponseHandler extends Handler{
19 |
20 | private ProgressHandler mProgressHandler;
21 | public ResponseHandler(ProgressHandler mProgressHandler, Looper looper) {
22 | super(looper);
23 | this.mProgressHandler = mProgressHandler;
24 | }
25 |
26 | @Override
27 | public void handleMessage(Message msg) {
28 | mProgressHandler.handleMessage(msg);
29 | }
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/library/src/main/java/com/ljd/retrofit/progress/ProgressHelper.java:
--------------------------------------------------------------------------------
1 | package com.ljd.retrofit.progress;
2 |
3 | import android.util.Log;
4 |
5 | import java.io.IOException;
6 |
7 | import okhttp3.Interceptor;
8 | import okhttp3.OkHttpClient;
9 |
10 | /**
11 | * Created by ljd on 4/12/16.
12 | */
13 | public class ProgressHelper {
14 |
15 | private static ProgressBean progressBean = new ProgressBean();
16 | private static ProgressHandler mProgressHandler;
17 |
18 | public static OkHttpClient.Builder addProgress(OkHttpClient.Builder builder){
19 |
20 | if (builder == null){
21 | builder = new OkHttpClient.Builder();
22 | }
23 |
24 | final ProgressListener progressListener = new ProgressListener() {
25 | //该方法在子线程中运行
26 | @Override
27 | public void onProgress(long progress, long total, boolean done) {
28 | Log.d("progress:",String.format("%d%% done\n",(100 * progress) / total));
29 | if (mProgressHandler == null){
30 | return;
31 | }
32 |
33 | progressBean.setBytesRead(progress);
34 | progressBean.setContentLength(total);
35 | progressBean.setDone(done);
36 | mProgressHandler.sendMessage(progressBean);
37 |
38 | }
39 | };
40 |
41 | //添加拦截器,自定义ResponseBody,添加下载进度
42 | builder.networkInterceptors().add(new Interceptor() {
43 | @Override
44 | public okhttp3.Response intercept(Chain chain) throws IOException {
45 | okhttp3.Response originalResponse = chain.proceed(chain.request());
46 | return originalResponse.newBuilder().body(
47 | new ProgressResponseBody(originalResponse.body(), progressListener))
48 | .build();
49 |
50 | }
51 | });
52 |
53 | return builder;
54 | }
55 |
56 | public static void setProgressHandler(ProgressHandler progressHandler){
57 | mProgressHandler = progressHandler;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/library/src/main/java/com/ljd/retrofit/progress/ProgressListener.java:
--------------------------------------------------------------------------------
1 | package com.ljd.retrofit.progress;
2 |
3 | /**
4 | * Created by ljd on 3/29/16.
5 | */
6 | public interface ProgressListener {
7 | /**
8 | * @param progress 已经下载或上传字节数
9 | * @param total 总字节数
10 | * @param done 是否完成
11 | */
12 | void onProgress(long progress, long total, boolean done);
13 | }
14 |
--------------------------------------------------------------------------------
/library/src/main/java/com/ljd/retrofit/progress/ProgressRequestBody.java:
--------------------------------------------------------------------------------
1 | package com.ljd.retrofit.progress;
2 |
3 | import java.io.IOException;
4 |
5 | import okhttp3.MediaType;
6 | import okhttp3.RequestBody;
7 | import okio.Buffer;
8 | import okio.BufferedSink;
9 | import okio.ForwardingSink;
10 | import okio.Okio;
11 | import okio.Sink;
12 |
13 | /**
14 | * Created by ljd on 4/18/16.
15 | */
16 | public class ProgressRequestBody extends RequestBody {
17 |
18 | private final RequestBody requestBody;
19 | private final ProgressListener progressListener;
20 | private BufferedSink bufferedSink;
21 |
22 | public ProgressRequestBody(RequestBody requestBody,ProgressListener progressListener){
23 | this.requestBody = requestBody;
24 | this.progressListener = progressListener;
25 | }
26 |
27 | @Override
28 | public MediaType contentType() {
29 | return requestBody.contentType();
30 | }
31 |
32 | @Override
33 | public long contentLength() throws IOException {
34 | return requestBody.contentLength();
35 | }
36 |
37 | @Override
38 | public void writeTo(BufferedSink sink) throws IOException {
39 | if (bufferedSink == null) {
40 |
41 | bufferedSink = Okio.buffer(sink(sink));
42 | }
43 |
44 | requestBody.writeTo(bufferedSink);
45 |
46 | bufferedSink.flush();
47 | }
48 |
49 | private Sink sink(Sink sink) {
50 | return new ForwardingSink(sink) {
51 |
52 | long bytesWritten = 0L;
53 | long contentLength = 0L;
54 |
55 | @Override
56 | public void write(Buffer source, long byteCount) throws IOException {
57 | super.write(source, byteCount);
58 | if (contentLength == 0) {
59 | contentLength = contentLength();
60 | }
61 |
62 | bytesWritten += byteCount;
63 | progressListener.onProgress(bytesWritten, contentLength, bytesWritten == contentLength);
64 | }
65 | };
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/library/src/main/java/com/ljd/retrofit/progress/ProgressResponseBody.java:
--------------------------------------------------------------------------------
1 | package com.ljd.retrofit.progress;
2 | import java.io.IOException;
3 |
4 | import okhttp3.MediaType;
5 | import okhttp3.ResponseBody;
6 | import okio.Buffer;
7 | import okio.BufferedSource;
8 | import okio.ForwardingSource;
9 | import okio.Okio;
10 | import okio.Source;
11 |
12 | /**
13 | * Created by ljd on 3/29/16.
14 | */
15 | public class ProgressResponseBody extends ResponseBody {
16 | private final ResponseBody responseBody;
17 | private final ProgressListener progressListener;
18 | private BufferedSource bufferedSource;
19 |
20 | public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) {
21 | this.responseBody = responseBody;
22 | this.progressListener = progressListener;
23 | }
24 |
25 | @Override
26 | public MediaType contentType() {
27 | return responseBody.contentType();
28 | }
29 |
30 | @Override
31 | public long contentLength() {
32 | return responseBody.contentLength();
33 | }
34 |
35 | @Override
36 | public BufferedSource source() {
37 | if (bufferedSource == null) {
38 | bufferedSource = Okio.buffer(source(responseBody.source()));
39 | }
40 | return bufferedSource;
41 | }
42 |
43 | private Source source(Source source) {
44 | return new ForwardingSource(source) {
45 | long totalBytesRead = 0L;
46 |
47 | @Override
48 | public long read(Buffer sink, long byteCount) throws IOException {
49 | long bytesRead = super.read(sink, byteCount);
50 | totalBytesRead += bytesRead != -1 ? bytesRead : 0;
51 | progressListener.onProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
52 | return bytesRead;
53 | }
54 | };
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/library/src/main/java/com/ljd/retrofit/progress/UploadProgressHandler.java:
--------------------------------------------------------------------------------
1 | package com.ljd.retrofit.progress;
2 |
3 | import android.os.Looper;
4 | import android.os.Message;
5 |
6 | /**
7 | * Created by ljd on 4/18/16.
8 | */
9 | public abstract class UploadProgressHandler extends ProgressHandler{
10 |
11 | private static final int UPLOAD_PROGRESS = 0;
12 | protected ResponseHandler mHandler = new ResponseHandler(this, Looper.getMainLooper());
13 |
14 | @Override
15 | protected void sendMessage(ProgressBean progressBean) {
16 | mHandler.obtainMessage(UPLOAD_PROGRESS,progressBean).sendToTarget();
17 |
18 | }
19 |
20 | @Override
21 | protected void handleMessage(Message message){
22 | switch (message.what){
23 | case UPLOAD_PROGRESS:
24 | ProgressBean progressBean = (ProgressBean)message.obj;
25 | onProgress(progressBean.getBytesRead(),progressBean.getContentLength(),progressBean.isDone());
26 | }
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/library/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Library
3 |
4 |
--------------------------------------------------------------------------------
/libs/android-async-http-1.4.9.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lijiangdong/retrofit-example/51d84874fb40146b1b842e0ae56b70d9e46ddc9d/libs/android-async-http-1.4.9.jar
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':library'
2 |
--------------------------------------------------------------------------------