1.基类
public class Base {
public static final String Url = "xxx";
}
2.API
public interface RequsetApi {
@Streaming
@POST("{fileName}")
Observable<ResponseBody> downloadFile(@Path("fileName") String fileName, @Header("Range") String range);
@Streaming
@POST("{fileName}")
Observable<ResponseBody> getFilelength(@Path("fileName") String fileName);
}
3.封装一个retrofit工具类
public class RetrofitUtils {
public static RequsetApi download(String basaUrl){
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(basaUrl)
.build();
RequsetApi requsetApi = retrofit.create(RequsetApi.class);
return requsetApi;
}
}
4.多线程下载任务
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(){
RetrofitUtils.download(Base.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();
}
}
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);
RetrofitUtils.download(Base.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(DialogUrils.PROGRESS<0){
DialogUrils.PROGRESS=0;
}
DialogUrils.PROGRESS+=len;
Log.i(Thread.currentThread() + "-----len-----", "onResponse: "+ startposition + len);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
5.弹出框和进度条设置
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() {
@Override
public 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>(){
@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();
}
}
6.mainActivity
public class MainActivity extends AppCompatActivity {
@BindView(R.id.vv)
VideoView vv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
DialogUrils.showUpdateDialog(this);
show();
}
public void show(){
// File file=new File(MainActivity.this.getCacheDir()+"/haha.mp4");
vv.setVideoPath(MainActivity.this.getCacheDir()+"/haha.mp4");
vv.start();
}
}
Retrofit多线程下载加进度条展示
最新推荐文章于 2021-05-26 07:10:07 发布