DownloadObservable.java 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. package com.mylove.okhttp;
  2. import android.annotation.SuppressLint;
  3. import android.content.Context;
  4. import android.support.annotation.NonNull;
  5. import java.io.File;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.util.concurrent.TimeUnit;
  10. import io.reactivex.Observable;
  11. import io.reactivex.ObservableEmitter;
  12. import io.reactivex.ObservableOnSubscribe;
  13. import io.reactivex.Observer;
  14. import io.reactivex.android.schedulers.AndroidSchedulers;
  15. import io.reactivex.disposables.Disposable;
  16. import io.reactivex.schedulers.Schedulers;
  17. import okhttp3.Call;
  18. import okhttp3.Callback;
  19. import okhttp3.OkHttpClient;
  20. import okhttp3.Request;
  21. import okhttp3.Response;
  22. /**
  23. * @author myLove
  24. */
  25. class DownloadObservable {
  26. @SuppressLint("StaticFieldLeak")
  27. private static DownloadObservable instance;
  28. @SuppressLint("StaticFieldLeak")
  29. private static Context mContext;
  30. private String filePath;
  31. private static OkHttpClient okHttpClient;
  32. private DownloadObservable() {
  33. }
  34. static DownloadObservable getInstance(Context context) {
  35. if (instance == null) {
  36. synchronized (DownloadObservable.class) {
  37. if (instance == null) {
  38. instance = new DownloadObservable();
  39. OkHttpClient httpClient = new OkHttpClient();
  40. okHttpClient = httpClient.newBuilder()
  41. .addNetworkInterceptor(new CacheInterceptor())
  42. .addInterceptor(Cache.HTTP_LOGGING_INTERCEPTOR)
  43. .cache(Cache.privateCache(context))
  44. .connectTimeout(30, TimeUnit.SECONDS)
  45. .readTimeout(30, TimeUnit.SECONDS)
  46. .build();
  47. }
  48. }
  49. }
  50. mContext = context;
  51. return instance;
  52. }
  53. void request(String url, String filePath, final OnDownloadListener onDownloadListener) {
  54. this.filePath = filePath;
  55. getObservable(url)
  56. .subscribeOn(Schedulers.io())
  57. .observeOn(AndroidSchedulers.mainThread())
  58. .subscribe(new Observer<DownloadBean>() {
  59. @Override
  60. public void onSubscribe(Disposable d) {
  61. }
  62. @Override
  63. public void onNext(DownloadBean bean) {
  64. if (OkHttpInfo.isLOG) {
  65. LogHelper.v(bean);
  66. }
  67. if (bean.status == 1) {
  68. onDownloadListener.onSuccess(bean.filePath);
  69. } else {
  70. onDownloadListener.onDownloading(bean.progress);
  71. }
  72. }
  73. @Override
  74. public void onError(Throwable e) {
  75. if (OkHttpInfo.isLOG)
  76. LogHelper.e(e.getMessage());
  77. onDownloadListener.onFailure(e);
  78. }
  79. @Override
  80. public void onComplete() {
  81. if (OkHttpInfo.isLOG)
  82. LogHelper.v("*****");
  83. onDownloadListener.onCompleted();
  84. }
  85. });
  86. }
  87. private Observable<DownloadBean> getObservable(final String url) {
  88. return Observable.create(new ObservableOnSubscribe<DownloadBean>() {
  89. @Override
  90. public void subscribe(ObservableEmitter<DownloadBean> e) {
  91. send(url, e);
  92. }
  93. });
  94. }
  95. private void send(final String url, ObservableEmitter<DownloadBean> subscriber) {
  96. InternetBean bean = Internet.ifInternet(mContext);
  97. if (bean.getStatus()) {
  98. Request request = new Request.Builder()
  99. .url(url)
  100. .build();
  101. Call call = okHttpClient.newCall(request);
  102. sendCall(url, call, subscriber);
  103. } else {
  104. subscriber.onError(new Exception(bean.getMsg()));
  105. }
  106. }
  107. /**
  108. * 请求
  109. */
  110. private void sendCall(final String url, Call call, final ObservableEmitter<DownloadBean> subscriber) {
  111. call.enqueue(new Callback() {
  112. @Override
  113. public void onFailure(@NonNull Call call, @NonNull IOException e) {
  114. if (OkHttpInfo.isLOG)
  115. LogHelper.e(e.getMessage());
  116. subscriber.onError(e);
  117. subscriber.onComplete();
  118. }
  119. @Override
  120. public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
  121. DownloadBean bean = new DownloadBean();
  122. InputStream is = null;
  123. byte[] buf = new byte[2048];
  124. int len = 0;
  125. FileOutputStream fos = null;
  126. // 储存下载文件的目录
  127. String savePath = FileUtil.isExistDir(filePath);
  128. try {
  129. is = response.body().byteStream();
  130. long total = response.body().contentLength();
  131. File file = new File(savePath, FileUtil.getNameFromUrl(url));
  132. bean.filePath = file.getAbsolutePath();
  133. if (OkHttpInfo.isLOG)
  134. LogHelper.d(filePath);
  135. fos = new FileOutputStream(file);
  136. long sum = 0;
  137. while ((len = is.read(buf)) != -1) {
  138. fos.write(buf, 0, len);
  139. sum += len;
  140. int progress = (int) (sum * 1.0f / total * 100);
  141. if (OkHttpInfo.isLOG)
  142. LogHelper.i(progress + "%");
  143. bean.status = 0;
  144. bean.progress = progress;
  145. if (OkHttpInfo.isLOG)
  146. LogHelper.d(bean);
  147. // 下载中
  148. subscriber.onNext(bean);
  149. }
  150. fos.flush();
  151. // 下载完成
  152. bean.status = 1;
  153. if (OkHttpInfo.isLOG)
  154. LogHelper.d(bean);
  155. subscriber.onNext(bean);
  156. subscriber.onComplete();
  157. } catch (Exception e) {
  158. if (OkHttpInfo.isLOG)
  159. LogHelper.e(e.getMessage());
  160. subscriber.onError(e);
  161. subscriber.onComplete();
  162. } finally {
  163. try {
  164. if (is != null)
  165. is.close();
  166. } catch (IOException e) {
  167. if (OkHttpInfo.isLOG)
  168. LogHelper.e(e.getMessage());
  169. }
  170. try {
  171. if (fos != null)
  172. fos.close();
  173. } catch (IOException e) {
  174. if (OkHttpInfo.isLOG)
  175. LogHelper.e(e.getMessage());
  176. }
  177. }
  178. }
  179. });
  180. }
  181. }