多线程下载httpurlConnection
来源:互联网 发布:nginx反向io代理 编辑:程序博客网 时间:2024/05/23 13:28
MainActivity中的代码package com.weektwopractise;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import com.weektwopractise.MoreXCDownload.DialogUtils;public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DialogUtils.ShowUpdateProgress(this); }}进度框的工具类代码package com.weektwopractise.MoreXCDownload;import android.annotation.SuppressLint;import android.app.ProgressDialog;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.net.Uri;import android.os.AsyncTask;import android.os.SystemClock;import android.support.v7.app.AlertDialog;import android.util.Log;import java.io.File;import java.io.IOException;/** * User: Moyuchen * Date: 2017-11-11 09:23 * Description: */public class DialogUtils { public static int MAX=0; public static int PROGRESS=-2; public static void ShowUpdateProgress(final Context context){ AlertDialog builder=new AlertDialog.Builder(context) .setTitle("版本有点低,请选择更新最新版本") .setPositiveButton("更新", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { new DownloadThread("http://169.254.35.159:8080/wyq/jinritoutiao_460.apk",context.getCacheDir()+"/d.apk",4).start(); showDownProgress(context,context.getCacheDir()+"/d.apk"); } }) .setNegativeButton("不用了",null) .show(); } private static void showDownProgress(final Context context, final String fileurl) { final ProgressDialog dialog=new ProgressDialog(context); dialog.setTitle("正在更新"); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setMax(100); dialog.show(); new AsyncTask<String, Integer, String>() { @SuppressLint("LongLogTag") @Override protected String doInBackground(String... strings) { Log.i("==========DialogUtils========", "doInBackground:+Progress: "+PROGRESS+"Max:"+MAX); while (PROGRESS<MAX) { Log.i("==========DialogUtils========", "doInBackground:+Progress: "+PROGRESS+"Max:"+MAX); SystemClock.sleep(100); if (MAX > 0) { publishProgress((int) (PROGRESS * 100 / MAX)); } else { publishProgress(0); } } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); dialog.dismiss(); File file=new File(fileurl); //重新给下载的文件设置权限 String[] command = {"chmod", "777", file.getPath() }; ProcessBuilder builder = new ProcessBuilder(command); try { builder.start(); } catch (IOException e) { e.printStackTrace(); } //设置跳转到系统安装页面 Intent intent = new Intent(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setDataAndType(Uri.parse("file://"+fileurl),"application/vnd.android.package-archive"); context.startActivity(intent); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); dialog.setProgress(values[0]); } }.execute(); }}下载线程中的代码package com.weektwopractise.MoreXCDownload;import android.annotation.SuppressLint;import android.util.Log;/** * User: Moyuchen * Date: 2017-11-11 08:42 * Description: */public class DownloadThread extends Thread{ private String downUrl=""; private int ThreadNum=5; private String path; public DownloadThread(String downUrl,String path,int threadNum){ this.downUrl=downUrl; this.path=path; this.ThreadNum=threadNum; } @SuppressLint("LongLogTag") @Override public void run() { super.run(); //获取要下载文件的长度,即大小 int fileLength = NetUtils.getFileContentLength(downUrl); DialogUtils.MAX=fileLength; Log.i("=============DownLoadThread===============", "fileLength: "+fileLength); int DownSize=fileLength/ThreadNum; for (int i=0;i<ThreadNum;i++){ int startPosition=i*DownSize; if (i==ThreadNum-1) { DownSize=fileLength-DownSize*(ThreadNum-1); } new DownTask(DownSize,downUrl,startPosition,path).start(); } }}下载任务中的代码package com.weektwopractise.MoreXCDownload;/** * User: Moyuchen * Date: 2017-11-11 09:00 * Description: */public class DownTask extends Thread { private int DownSize; private String DownUrl; private int startPosition; private String path; public DownTask(int downSize, String downUrl, int startPosition, String path) { DownSize = downSize; DownUrl = downUrl; this.startPosition = startPosition; this.path = path; } @Override public void run() { super.run(); NetUtils.DownLoad(DownUrl,DownSize,path,startPosition); }}网络下载类中的代码package com.weektwopractise.MoreXCDownload;import java.io.BufferedInputStream;import java.io.File;import java.io.IOException;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.URL;/** * User: Moyuchen * Date: 2017-11-11 08:49 * Description: */public class NetUtils { /** * 获取要下的文件的长度 * @param downloadUrl * @return */ public static int getFileContentLength(String downloadUrl){ int contentLength=0; try { URL url=new URL(downloadUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(5000); con.setConnectTimeout(5000); //获取下载的长度 contentLength = con.getContentLength(); } catch (Exception e) { e.printStackTrace(); } return contentLength; } public static void DownLoad(String downUrl,int DownSize,String path,int startPosition){ BufferedInputStream buffer = null; RandomAccessFile raf = null; try { File file=new File(path); if (!file.exists()) { file.createNewFile(); } URL url=new URL(downUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(5000); con.setReadTimeout(5000); if (DownSize>0) { int endPosition=DownSize+startPosition-1; con.setRequestProperty("Range","bytes="+startPosition+"-"+endPosition); } int responseCode = con.getResponseCode();//获取响应码 if (400>responseCode) { buffer = new BufferedInputStream(con.getInputStream()); raf = new RandomAccessFile(file, "rwd"); raf.seek(startPosition); int len=0; byte[] bytes=new byte[1024*8]; while ((len=buffer.read(bytes))!=-1){ synchronized (NetUtils.class){ raf.write(bytes,0,len); if (DialogUtils.PROGRESS<0) { DialogUtils.PROGRESS=0; } DialogUtils.PROGRESS+=len; } } } } catch (Exception e) { e.printStackTrace(); }finally { if (buffer!=null) { try { buffer.close(); } catch (IOException e) { e.printStackTrace(); } } if (raf!=null) { try { raf.close(); } catch (IOException e) { e.printStackTrace(); } } } }}最后设置权限<uses-permission android:name="android.permission.INTERNET"/>//网络权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>//SD卡读写权限<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
阅读全文
0 0
- HttpURLConnection多线程下载
- HttpURLConnection多线程下载
- HttpURLConnection实现多线程下载
- Java HttpUrlConnection多线程下载
- Android HttpURLConnection 多线程下载
- android多线程下载-HttpURLConnection
- 多线程下载httpurlConnection
- 使用HttpURLConnection实现多线程下载
- android HttpURLConnection实现多线程下载
- HttpURLConnection(四)-多线程下载
- HttpURLConnection实现多线程网络下载
- HttpUrlConnection实现多线程下载网络资源
- 使用HttpUrlConnection多线程下载文件
- android多线程暂停下载-HttpURLConnection
- Android 使用HttpURLConnection实现多线程下载 笔记
- 多线程断点下载-handler-thread-HttpURLConnection
- android中使用HttpURLConnection实现多线程下载
- HttpURLConnection实现多线程下载资源contentLength()
- redis分布式锁
- 深入浅出之时间线(一)
- redis分布式锁实现
- sd卡烧录系统后容量下降解决办法
- Qt之根据扩展名获取文件图标、类型
- 多线程下载httpurlConnection
- 普通二极管伏安特性和肖特基二极管电压电流特性
- 【观察】联想数据中心业务整体布局见成效 背后的动能和势能
- Scrapy架构简述
- NOIP2017 游记 Day 1
- 该如何学习java-IO流
- U3D Shader Forward Path光源存储信息
- Boyer-Moore BM算法(普林斯顿算法课Algorithm2-part II:Substring Search)
- C++创建对象及注意事项