admin管理员组

文章数量:814275

Retrofit+多线程下载

加载的网址方法

public class connect {public static final String Url = "http://169.254.51.153:8080/";}

retrofit的封装

package com.example.myretrofit.api;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Header;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Streaming;
import rx.Observable;
public interface HomeApi {@Streaming@POST("{fileName}")Observable<ResponseBody> downloadFile(@Path("fileName") String fileName, @Header("Range") String range);@Streaming@POST("{fileName}")Observable<ResponseBody> getFilelength(@Path("fileName") String fileName);OkHttpClient client=new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).readTimeout(5,TimeUnit.SECONDS).build();Retrofit RETROFIT=new Retrofit.Builder().client(client).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).baseUrl(connect.Url).build();HomeApi requsetApi = RETROFIT.create(HomeApi.class);
}

DownloadThread

package com.example.myretrofit;
import android.util.Log;
import com.example.myretrofit.api.HomeApi;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import okhttp3.ResponseBody;
import rx.Observer;
import rx.schedulers.Schedulers;public class DownloadThread{private String downloadUrl="";private String path;private int threadNum=5;long length;public DownloadThread(String downloadUrl, String path) {this.downloadUrl = downloadUrl;this.path = path;}public void show(){HomeApi.requsetApi.getFilelength(downloadUrl).observeOn(Schedulers.io()).subscribeOn(Schedulers.io()).subscribe(new Observer<ResponseBody>() {@Overridepublic void onCompleted() {}@Overridepublic void onError(Throwable throwable) {Log.i("-----onError-------", "onError: "+throwable.getMessage());}@Overridepublic void onNext(ResponseBody responseBody) {length=responseBody.contentLength();downoadTask(length);}});}public void downoadTask(Long length){final File file=new File(path);if(!file.exists()){try {file.createNewFile();} catch (IOException e) {e.printStackTrace();}}DialogUrils.MAX_SIZE=length;Log.i("------length-------", "downoadTask: "+length);long blockSize=length/threadNum;for (int i = 0; i < threadNum; i++) {final long startposition=blockSize*i;if(i==threadNum-1){blockSize=length-blockSize*(threadNum-1);}String range="bytes="+startposition+"-"+(startposition+blockSize-1);Log.i("------range-------", "downoadTask: "+range);HomeApi.requsetApi.downloadFile(downloadUrl,range).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Observer<ResponseBody>() {@Overridepublic void onCompleted() {}@Overridepublic void onError(Throwable throwable) {Log.i("-----error-----", "onResponse: "+throwable.getMessage());}@Overridepublic void onNext(ResponseBody responseBody) {try {Log.i("-----error-----", "onResponse: "+"进来了");BufferedInputStream bis=new BufferedInputStream(responseBody.byteStream());RandomAccessFile raf=new RandomAccessFile(file,"rwd");raf.seek(startposition);byte[] buff=new byte[1024*8];int len=0;while ((len=bis.read(buff))!=-1){raf.write(buff,0,len);if(DialogUrils.PROGRESS<0){DialogUrils.PROGRESS=0;}DialogUrils.PROGRESS+=len;Log.i(Thread.currentThread() + "-----len-----", "onResponse: "+ startposition + len);}} catch (Exception e) {e.printStackTrace();}}});}}
}

DialogUrils

package com.example.myretrofit;import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.SystemClock;public class DialogUrils {public static long MAX_SIZE=0;public static long PROGRESS=-2;public static void showUpdateDialog(final Context context){new AlertDialog.Builder(context).setTitle("更新吧").setNegativeButton("就不",null).setPositiveButton("好吧", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {DownloadThread downloadThread=new DownloadThread("马丁·路德·金:我有一个梦想.mp4",context.getCacheDir()+"/haha.mp4");downloadThread.show();showProgress(context);}}).show();}public static void showProgress(Context context){final ProgressDialog pd=new ProgressDialog(context);pd.setTitle("正在更新");pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);pd.setMax(100);pd.show();new AsyncTask<String,Integer,String>(){@Overrideprotected String doInBackground(String... params) {while (PROGRESS+1<MAX_SIZE){SystemClock.sleep(10);if(MAX_SIZE>0){publishProgress((int)(PROGRESS*100/MAX_SIZE));}}return null;}@Overrideprotected void onProgressUpdate(Integer... values) {super.onProgressUpdate(values);pd.setProgress(values[0]);}}.execute();}
}

MainActivity
一个是下载sd卡,一是从路径里直接取出来

package com.example.myretrofit;import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.VideoView;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// DialogUrils.showUpdateDialog(this);show();}private void show() {VideoView vv= (VideoView) findViewById(R.id.vv);vv.setVideoPath(MainActivity.this.getCacheDir()+"/haha.mp4");vv.start();}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android=""xmlns:app=""xmlns:tools="" android:layout_width="match_parent"android:layout_height="match_parent" tools:context="com.example.myretrofit.MainActivity"><VideoView
        android:id="@+id/vv"android:layout_width="400dp"android:layout_height="300dp" /></RelativeLayout>

本文标签: Retrofit多线程下载