80,337
社区成员
发帖
与我相关
我的任务
分享
public abstract class FileDownLoadSubscriber extends DisposableSubscriber<ResponseBody> {
private File file;
public FileDownLoadSubscriber(File file) {
this.file = file;
}
@Override
public void onNext(ResponseBody body) {
new WriteFile(file,body,this).execute();
}
@Override
public void onError(Throwable t) {
onFail("下载失败");
}
@Override
public void onComplete() {
}
private class WriteFile extends AsyncTask<String, Long, Boolean>{
private File file;
private ResponseBody body;
private FileDownLoadSubscriber subscriber;
public WriteFile(File file, ResponseBody body, FileDownLoadSubscriber subscriber) {
this.file = file;
this.body = body;
this.subscriber = subscriber;
}
@Override
protected Boolean doInBackground(String... strings) {
InputStream input = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try{
input = body.byteStream();
final long total = body.contentLength();
long sum = 0;
File dir = file.getParentFile();
if (!dir.exists()){
if (!dir.mkdirs()) return false;
}
fos = new FileOutputStream(file);
while ((len = input.read(buf))!=-1){
sum += len;
fos.write(buf,0,len);
final long finalSum = sum;
publishProgress(finalSum, total);
}
fos.flush();
return true;
} catch (Exception ex){
return false;
}finally {
try{
if (input != null) input.close();
if (fos != null) fos.close();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
@Override
protected void onProgressUpdate(Long... values) {
subscriber.onProgress(values[0], values[1]);
}
@Override
protected void onPostExecute(Boolean result) {
if (result){
subscriber.onProgress(file.length(), file.length());
subscriber.onSuccess(file);
} else {
subscriber.onFail("下载失败");
}
}
}
public void onSuccess(File file){}
public void onFail(String msg){}
public void onProgress(long current,long total){}
}
ApiService代码
public interface ApiService {
@Streaming
@GET
Flowable<ResponseBody> downLoad(@Url String url);
}
RetrofitUtils代码
public class RetrofitUtils {
private static final Retrofit.Builder builder;
static {
builder = new Retrofit.Builder().client(new OkHttpClient.Builder().build()).
addCallAdapterFactory(RxJava2CallAdapterFactory.create()).
addConverterFactory(FastJsonConverterFactory.create());
}
public static void buildBaseUrl(String baseUrl) {
builder.baseUrl(baseUrl);
}
public static <T> T createService(Class<T> serviceClass){
return builder.build().create(serviceClass);
}
}
RequestUtil代码
public class RequestUtil {
static {
// 配置自己的baseurl,因为这个必须配置,自己配置就行了。
RetrofitUtils.buildBaseUrl("http://baidu.com");
}
private static final ApiService apiService = RetrofitUtils.createService(ApiService.class);
private static FlowableTransformer<ResponseBody, ResponseBody> ioMainDownload(){
return new FlowableTransformer<ResponseBody, ResponseBody>() {
@Override
public Publisher<ResponseBody> apply(Flowable<ResponseBody> upstream) {
return upstream.subscribeOn(Schedulers.io()).
observeOn(Schedulers.io()).
observeOn(Schedulers.computation()).
map(new Function<ResponseBody, ResponseBody>() {
@Override
public ResponseBody apply(ResponseBody responseBody) throws Exception {
return responseBody;
}
}).
observeOn(AndroidSchedulers.mainThread());
}
};
}
public static FileDownLoadSubscriber downLoad(FileDownLoadSubscriber subscriber,String url){
return apiService.downLoad(url).
compose(ioMainDownload()).
subscribeWith(subscriber);
}
}
使用方法,Activity中调用
File file = new File(getFilesDir(),"test.jpg");
RequestUtil.downLoad(new FileDownLoadSubscriber(file) {
@Override
public void onSuccess(File file) {
Toast.makeText(TestActivity.this, "下载成功", Toast.LENGTH_LONG).show();
}
@Override
public void onFail(String msg) {
Toast.makeText(TestActivity.this, msg, Toast.LENGTH_LONG).show();
}
@Override
public void onProgress(long current, long total) {
textView.setText(current+"/"+total);
}
},"http://f.hiphotos.baidu.com/image/pic/item/503d269759ee3d6db032f61b48166d224e4ade6e.jpg");
这个图片可能比较小,网速比较快的时候看不到效果,可以自己改地址