java语言之基于Retrofit+Rxjava实现带进度显示的下载文件
龚超 2018-07-09 来源 : 阅读 1252 评论 0

摘要:本文实例为大家分享了java语言的Retrofit Rxjava实现下载文件的具体代码,供大家参考,具体内容如下,希望对大家学习java语言有所帮助。

本文实例为大家分享了java语言的Retrofit Rxjava实现下载文件的具体代码,供大家参考,具体内容如下,希望对大家学习java语言有所帮助。

本文采用 :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.CreatorCREATOR = 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
Observabledownload(@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 = "//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);
}
}
复制代码

希望对JAVA有兴趣的朋友有所帮助。了解更多内容,请关注职坐标编程语言JAVA频道!

本文由 @职坐标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论
本文作者 联系TA

擅长针对企业软件开发的产品设计及开发的细节与流程设计课程内容。座右铭:大道至简!

  • 370
    文章
  • 23049
    人气
  • 87%
    受欢迎度

已有23人表明态度,87%喜欢该老师!

进入TA的空间
求职秘籍 直通车
  • 索取资料 索取资料 索取资料
  • 答疑解惑 答疑解惑 答疑解惑
  • 技术交流 技术交流 技术交流
  • 职业测评 职业测评 职业测评
  • 面试技巧 面试技巧 面试技巧
  • 高薪秘笈 高薪秘笈 高薪秘笈
TA的其他文章 更多>>
WEB前端必须会的基本知识题目
经验技巧 93% 的用户喜欢
Java语言中四种遍历List的方法总结(推荐)
经验技巧 91% 的用户喜欢
Java语言之SHA-256加密的两种实现方法详解
经验技巧 75% 的用户喜欢
java语言实现把两个有序数组合并到一个数组的实例
经验技巧 75% 的用户喜欢
通过Java语言代码来创建view的方法
经验技巧 80% 的用户喜欢
其他海同师资 更多>>
吕益平
吕益平 联系TA
熟悉企业软件开发的产品设计及开发
孔庆琦
孔庆琦 联系TA
对MVC模式和三层架构有深入的研究
周鸣君
周鸣君 联系TA
擅长Hadoop/Spark大数据技术
范佺菁
范佺菁 联系TA
擅长Java语言,只有合理的安排和管理时间你才能做得更多,行得更远!
金延鑫
金延鑫 联系TA
擅长与学生或家长及时有效沟通
经验技巧30天热搜词 更多>>

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程