多线程下载httpurlConnection
2017-11-11 13:38
337 查看
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 c2e0 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"/>
相关文章推荐
- Android-使用HttpURLConnection实现多线程下载
- Android开发_使用HttpURLConnection实现多线程下载
- 安卓基础:HttpURLConnection实现多线程下载
- android多线程下载-HttpURLConnection
- Android 使用HttpURLConnection实现多线程下载 笔记
- HttpURLConnection多线程下载
- Android HttpURLConnection 多线程下载
- android中使用HttpURLConnection实现多线程下载
- Android 使用HttpURLConnection 实现多线程下载
- HttpURLConnection(四)-多线程下载
- HttpURLConnection方式文件下载之多线程下载
- Java HttpUrlConnection多线程下载
- HttpURLConnection多线程下载
- HttpURLConnection实现多线程下载资源contentLength()
- Android上Java网络资源访问(二)使用HttpURLConnection多线程下载
- get和post请求(HttpUrlConnection、HttpClient、AsyncHttpClient)多线程下载,断点续传
- 使用HttpURLConnection实现多线程下载
- android HttpURLConnection实现多线程下载
- HttpURLConnection实现多线程下载
- HttpURLConnection之断点续传(多线程下载)