热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

基于Retrofit+Rxjava实现带进度显示的下载文件

这篇文章主要为大家详细介绍了基于Retrofit+Rxjava实现带进度显示的下载文件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Retrofit Rxjava实现下载文件的具体代码,供大家参考,具体内容如下

本文采用 :retrofit + rxjava

1.引入:

//rxJava
 compile 'io.reactivex:rxjava:latest.release'
 compile 'io.reactivex:rxandroid:latest.release'
 //network - squareup
 compile 'com.squareup.retrofit2:retrofit:latest.release'
 compile 'com.squareup.retrofit2:adapter-rxjava:latest.release'
 compile 'com.squareup.okhttp3:okhttp:latest.release'
 compile 'com.squareup.okhttp3:logging-interceptor:latest.release'

2.增加下载进度监听:

public interface DownloadProgressListener {
 void update(long bytesRead, long contentLength, boolean done);
}
public class DownloadProgressResponseBody extends ResponseBody {

 private ResponseBody responseBody;
 private DownloadProgressListener progressListener;
 private BufferedSource bufferedSource;

 public DownloadProgressResponseBody(ResponseBody responseBody,
          DownloadProgressListener progressListener) {
  this.respOnseBody= responseBody;
  this.progressListener = progressListener;
 }

 @Override
 public MediaType contentType() {
  return responseBody.contentType();
 }

 @Override
 public long contentLength() {
  return responseBody.contentLength();
 }

 @Override
 public BufferedSource source() {
  if (bufferedSource == null) {
   bufferedSource = Okio.buffer(source(responseBody.source()));
  }
  return bufferedSource;
 }

 private Source source(Source source) {
  return new ForwardingSource(source) {
   long totalBytesRead = 0L;

   @Override
   public long read(Buffer sink, long byteCount) throws IOException {
    long bytesRead = super.read(sink, byteCount);
    // read() returns the number of bytes read, or -1 if this source is exhausted.
    totalBytesRead += bytesRead != -1 ? bytesRead : 0;

    if (null != progressListener) {
     progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
    }
    return bytesRead;
   }
  };

 }
}

public class DownloadProgressInterceptor implements Interceptor {

 private DownloadProgressListener listener;

 public DownloadProgressInterceptor(DownloadProgressListener listener) {
  this.listener = listener;
 }

 @Override
 public Response intercept(Chain chain) throws IOException {
  Response originalRespOnse= chain.proceed(chain.request());

  return originalResponse.newBuilder()
    .body(new DownloadProgressResponseBody(originalResponse.body(), listener))
    .build();
 }
}

3.创建下载进度的元素类:

public class Download implements Parcelable {

 private int progress;
 private long currentFileSize;
 private long totalFileSize;

 public int getProgress() {
  return progress;
 }

 public void setProgress(int progress) {
  this.progress = progress;
 }

 public long getCurrentFileSize() {
  return currentFileSize;
 }

 public void setCurrentFileSize(long currentFileSize) {
  this.currentFileSize = currentFileSize;
 }

 public long getTotalFileSize() {
  return totalFileSize;
 }

 public void setTotalFileSize(long totalFileSize) {
  this.totalFileSize = totalFileSize;
 }

 @Override
 public int describeContents() {
  return 0;
 }

 @Override
 public void writeToParcel(Parcel dest, int flags) {
  dest.writeInt(this.progress);
  dest.writeLong(this.currentFileSize);
  dest.writeLong(this.totalFileSize);
 }

 public Download() {
 }

 protected Download(Parcel in) {
  this.progress = in.readInt();
  this.currentFileSize = in.readLong();
  this.totalFileSize = in.readLong();
 }

 public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
  @Override
  public Download createFromParcel(Parcel source) {
   return new Download(source);
  }

  @Override
  public Download[] newArray(int size) {
   return new Download[size];
  }
 };
}

4.下载文件网络类:

public interface DownloadService {

 @Streaming
 @GET
 Observable download(@Url String url);
}

注:这里@Url是传入完整的的下载URL;不用截取

public class DownloadAPI {
 private static final String TAG = "DownloadAPI";
 private static final int DEFAULT_TIMEOUT = 15;
 public Retrofit retrofit;


 public DownloadAPI(String url, DownloadProgressListener listener) {

  DownloadProgressInterceptor interceptor = new DownloadProgressInterceptor(listener);

  OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(interceptor)
    .retryOnConnectionFailure(true)
    .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
    .build();


  retrofit = new Retrofit.Builder()
    .baseUrl(url)
    .client(client)
    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
    .build();
 }

 public void downloadAPK(@NonNull String url, final File file, Subscriber subscriber) {
  Log.d(TAG, "downloadAPK: " + url);

  retrofit.create(DownloadService.class)
    .download(url)
    .subscribeOn(Schedulers.io())
    .unsubscribeOn(Schedulers.io())
    .map(new Func1() {
     @Override
     public InputStream call(ResponseBody responseBody) {
      return responseBody.byteStream();
     }
    })
    .observeOn(Schedulers.computation())
    .doOnNext(new Action1() {
     @Override
     public void call(InputStream inputStream) {
      try {
       FileUtils.writeFile(inputStream, file);
      } catch (IOException e) {
       e.printStackTrace();
       throw new CustomizeException(e.getMessage(), e);
      }
     }
    })
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(subscriber);
 }


}

然后就是调用了:

该网络是在service里完成的

public class DownloadService extends IntentService {
 private static final String TAG = "DownloadService";

 private NotificationCompat.Builder notificationBuilder;
 private NotificationManager notificationManager;


 private String apkUrl = "http://download.fir.im/v2/app/install/595c5959959d6901ca0004ac?download_token=1a9dfa8f248b6e45ea46bc5ed96a0a9e&source=update";

 public DownloadService() {
  super("DownloadService");
 }

 @Override
 protected void onHandleIntent(Intent intent) {
  notificatiOnManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

  notificatiOnBuilder= new NotificationCompat.Builder(this)
    .setSmallIcon(R.mipmap.ic_download)
    .setContentTitle("Download")
    .setContentText("Downloading File")
    .setAutoCancel(true);

  notificationManager.notify(0, notificationBuilder.build());

  download();
 }

 private void download() {
  DownloadProgressListener listener = new DownloadProgressListener() {
   @Override
   public void update(long bytesRead, long contentLength, boolean done) {
    Download download = new Download();
    download.setTotalFileSize(contentLength);
    download.setCurrentFileSize(bytesRead);
    int progress = (int) ((bytesRead * 100) / contentLength);
    download.setProgress(progress);

    sendNotification(download);
   }
  };
  File outputFile = new File(Environment.getExternalStoragePublicDirectory
    (Environment.DIRECTORY_DOWNLOADS), "file.apk");
  String baseUrl = StringUtils.getHostName(apkUrl);

  new DownloadAPI(baseUrl, listener).downloadAPK(apkUrl, outputFile, new Subscriber() {
   @Override
   public void onCompleted() {
    downloadCompleted();
   }

   @Override
   public void onError(Throwable e) {
    e.printStackTrace();
    downloadCompleted();
    Log.e(TAG, "onError: " + e.getMessage());
   }

   @Override
   public void onNext(Object o) {

   }
  });
 }

 private void downloadCompleted() {
  Download download = new Download();
  download.setProgress(100);
  sendIntent(download);

  notificationManager.cancel(0);
  notificationBuilder.setProgress(0, 0, false);
  notificationBuilder.setContentText("File Downloaded");
  notificationManager.notify(0, notificationBuilder.build());
 }

 private void sendNotification(Download download) {

  sendIntent(download);
  notificationBuilder.setProgress(100, download.getProgress(), false);
  notificationBuilder.setContentText(
    StringUtils.getDataSize(download.getCurrentFileSize()) + "/" +
      StringUtils.getDataSize(download.getTotalFileSize()));
  notificationManager.notify(0, notificationBuilder.build());
 }

 private void sendIntent(Download download) {

  Intent intent = new Intent(MainActivity.MESSAGE_PROGRESS);
  intent.putExtra("download", download);
  LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
 }

 @Override
 public void onTaskRemoved(Intent rootIntent) {
  notificationManager.cancel(0);
 }
}

MainActivity代码:

public class MainActivity extends AppCompatActivity {

 public static final String MESSAGE_PROGRESS = "message_progress";

 private AppCompatButton btn_download;
 private ProgressBar progress;
 private TextView progress_text;


 private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {

   if (intent.getAction().equals(MESSAGE_PROGRESS)) {

    Download download = intent.getParcelableExtra("download");
    progress.setProgress(download.getProgress());
    if (download.getProgress() == 100) {

     progress_text.setText("File Download Complete");

    } else {

     progress_text.setText(StringUtils.getDataSize(download.getCurrentFileSize())
       +"/"+
       StringUtils.getDataSize(download.getTotalFileSize()));

    }
   }
  }
 };

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  btn_download = (AppCompatButton) findViewById(R.id.btn_download);
  progress = (ProgressBar) findViewById(R.id.progress);
  progress_text = (TextView) findViewById(R.id.progress_text);

  registerReceiver();

  btn_download.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    Intent intent = new Intent(MainActivity.this, DownloadService.class);
    startService(intent);
   }
  });
 }

 private void registerReceiver() {

  LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
  IntentFilter intentFilter = new IntentFilter();
  intentFilter.addAction(MESSAGE_PROGRESS);
  bManager.registerReceiver(broadcastReceiver, intentFilter);

 }
}

本文源码:Retrofit Rxjava实现下载文件

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


推荐阅读
  • Monkey《大话移动——Android与iOS应用测试指南》的预购信息发布啦!
    Monkey《大话移动——Android与iOS应用测试指南》的预购信息已经发布,可以在京东和当当网进行预购。感谢几位大牛给出的书评,并呼吁大家的支持。明天京东的链接也将发布。 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文讲述了如何通过代码在Android中更改Recycler视图项的背景颜色。通过在onBindViewHolder方法中设置条件判断,可以实现根据条件改变背景颜色的效果。同时,还介绍了如何修改底部边框颜色以及提供了RecyclerView Fragment layout.xml和项目布局文件的示例代码。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • 【Windows】实现微信双开或多开的方法及步骤详解
    本文介绍了在Windows系统下实现微信双开或多开的方法,通过安装微信电脑版、复制微信程序启动路径、修改文本文件为bat文件等步骤,实现同时登录两个或多个微信的效果。相比于使用虚拟机的方法,本方法更简单易行,适用于任何电脑,并且不会消耗过多系统资源。详细步骤和原理解释请参考本文内容。 ... [详细]
  • Android Studio Bumblebee | 2021.1.1(大黄蜂版本使用介绍)
    本文介绍了Android Studio Bumblebee | 2021.1.1(大黄蜂版本)的使用方法和相关知识,包括Gradle的介绍、设备管理器的配置、无线调试、新版本问题等内容。同时还提供了更新版本的下载地址和启动页面截图。 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
author-avatar
手机用户2702932800
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有