一:Retrofit的接口
public interface ReqestApi {
//获得每个线程长度
@Streaming
@GET("{fileName}")
Observable<ResponseBody> downloadFile(@Path("fileName") String fileName, @Header("Range") String range);
//获得文件总长
@Streaming
@GET("{fileName}")
Observable<ResponseBody> getFilelength(@Path("fileName") String fileName);
}
二:Retrofit的封装
public class RetrofitUtils {
public static ReqestApi download(String basaUrl){
OkHttpClient client=new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build();
//Retrofit的配置
Retrofit retrofit=new Retrofit.Builder()
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(basaUrl)
.build();
ReqestApi reqestApi = retrofit.create(ReqestApi.class);
return reqestApi;
}
}
三:线程类
public class DownloadThread extends Thread{
private String downloadUrl="";
private String path;
private int threadNum=5;
long length;
public static final String Url = "http://gdown.baidu.com/data/wisegame/d2fbbc8e64990454/";
public DownloadThread(String downloadUrl, String path) {
this.downloadUrl = downloadUrl;
this.path = path;
}
public void show(){
//获得文件的总长 RetrofitUtils.download(Url).getFilelength(downloadUrl).observeOn(Schedulers.io()).subscribeOn(Schedulers.io()).subscribe(new Observer<ResponseBody>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable throwable) {
Log.i("-----onError-------", "onError: "+throwable.getMessage());
}
@Override
public 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();
}
}
DialogUtils.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);
RetrofitUtils.download(Url).downloadFile(downloadUrl,range).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Observer<ResponseBody>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable throwable) {
Log.i("-----error-----", "onResponse: "+throwable.getMessage());
}
@Override
public 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(DialogUtils.PROGRESS<0){
DialogUtils.PROGRESS=0;
}
DialogUtils.PROGRESS+=len;
Log.i(Thread.currentThread() + "-----len-----", "onResponse: "+ startposition + len);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
五:dialog类
class DialogUtils {
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() {
@Override
public void onClick(DialogInterface dialog, int which) {
//// TODO: 2017/11/22
DownloadThread downloadThread=new DownloadThread("wangyiyunyinle_87.apk",context.getCacheDir()+"/hahah.apk");
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>(){
@Override
protected String doInBackground(String... params) {
while (PROGRESS+1<MAX_SIZE){
SystemClock.sleep(10);
if(MAX_SIZE>0){
publishProgress((int)(PROGRESS*100/MAX_SIZE));
}
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pd.setProgress(values[0]);
}
}.execute();
}
}
mainactivity调用dialogutil