Android&多线程下载
FileDownloadThread.java
1 package com.zachary.mutildownloader; 2 3 import java.io.BufferedInputStream; 4 import java.io.File; 5 import java.io.IOException; 6 import java.io.RandomAccessFile; 7 import java.net.URL; 8 import java.net.URLConnection; 9 10 import android.util.Log; 11 12 public class FileDownloadThread extends Thread { 13 private static final int BUFFER_SIZE = 1024; 14 private URL url; 15 private File file; 16 private int startPosition; 17 private int endPosition; 18 private int curPosition; 19 //用于标示当前线程是否下载完成 20 private boolean finished = false; 21 private int downloadSize = 0; 22 23 final static String TAG = "LOGCAT"; 24 25 public FileDownloadThread(URL url, File file, int startPosition, int endPosition){ 26 this.url = url; 27 this.file = file; 28 this.startPosition = startPosition; 29 this.curPosition = startPosition; 30 this.endPosition = endPosition; 31 } 32 33 @Override 34 public void run() { 35 // TODO Auto-generated method stub 36 BufferedInputStream bis = null; 37 RandomAccessFile fos = null; 38 byte[] buf = new byte[BUFFER_SIZE]; 39 URLConnection con = null; 40 try { 41 con = url.openConnection(); 42 con.setAllowUserInteraction(true); 43 Log.i(TAG, "con.setAllowUserInteraction(true);"); 44 //设置当前线程下载的起点,终点 45 con.setRequestProperty("Range", "bytes=" + startPosition + "-" + endPosition); 46 47 //使用java中的RandomAccessFile 对文件进行随机读写操作 48 fos = new RandomAccessFile(file, "rw"); 49 //设置开始写文件的位置 50 fos.seek(startPosition); 51 bis = new BufferedInputStream(con.getInputStream()); 52 //开始循环以流的形式读写文件 53 while(curPosition < endPosition) { 54 int len = bis.read(buf, 0, BUFFER_SIZE); 55 if(len == -1) 56 break; 57 fos.write(buf, 0, len); 58 curPosition = curPosition + len; 59 if(curPosition > endPosition){ 60 downloadSize += len - (curPosition - endPosition) + 1; 61 }else { 62 downloadSize += len; 63 } 64 } 65 this.finished = true; 66 Log.i(TAG, "the thread was finished"); 67 bis.close(); 68 fos.close(); 69 } catch (IOException e) { 70 // TODO Auto-generated catch block 71 e.printStackTrace(); 72 Log.d(getName() +" Error:", e.getMessage()); 73 } 74 } 75 76 public boolean isFinished() { 77 return finished; 78 } 79 80 public int getDownloadSize() { 81 return downloadSize; 82 } 83 }
MainActivity.java
1 package com.zachary.mutildownloader; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.net.MalformedURLException; 6 import java.net.URL; 7 import java.net.URLConnection; 8 9 import android.app.Activity; 10 import android.os.Bundle; 11 import android.os.Environment; 12 import android.os.Handler; 13 import android.os.Message; 14 import android.util.Log; 15 import android.view.Menu; 16 import android.view.View; 17 import android.view.View.OnClickListener; 18 import android.widget.Button; 19 import android.widget.ProgressBar; 20 import android.widget.TextView; 21 import android.widget.Toast; 22 23 public class MainActivity extends Activity { 24 25 private Button downloadBtn = null; 26 private ProgressBar downloadProgressBar = null; 27 private TextView myTextView = null; 28 private int downloadedSize = 0; 29 private int fileSize = 0; 30 31 final static String TAG = "LOGCAT"; 32 33 @Override 34 protected void onCreate(Bundle savedInstanceState) { 35 super.onCreate(savedInstanceState); 36 setContentView(R.layout.activity_main); 37 38 downloadBtn = (Button)findViewById(R.id.downloadButton); 39 downloadProgressBar = (ProgressBar)findViewById(R.id.downloadBar); 40 myTextView = (TextView)findViewById(R.id.myTextView); 41 downloadProgressBar.setVisibility(View.VISIBLE); 42 downloadProgressBar.setProgress(0); 43 44 downloadBtn.setOnClickListener(new OnClickListener() { 45 46 @Override 47 public void onClick(View arg0) { 48 // TODO Auto-generated method stub 49 String urlStr = "http://zhangmenshiting.baidu.com/data2/music/35420301/35420301.mp3?xcode=54e756b52270bf9f05efbff149ebffea&mid=0.05505464576834"; 50 download(urlStr); 51 } 52 53 }); 54 55 } 56 57 private void download(String urlStr){ 58 String downloadDir = Environment.getExternalStorageDirectory() + "/myDownload/"; 59 File file = new File(downloadDir); 60 if(!file.exists()){ 61 file.mkdirs(); 62 Toast.makeText(MainActivity.this,"make the Dir", Toast.LENGTH_LONG).show(); 63 } 64 String fileName = "abc.mp3"; 65 downloadBtn.setClickable(false); 66 downloadProgressBar.setProgress(0); 67 new downloadTask(urlStr, 5, downloadDir + fileName).start(); 68 Log.i(TAG,"Begin to download"); 69 } 70 71 72 Handler handler = new Handler() { 73 @Override 74 public void handleMessage(Message msg) { 75 //当收到更新视图消息时,计算已完成下载百分比,同时更新进度条信息 76 int progress = (Double.valueOf((downloadedSize * 1.0 / fileSize * 100))).intValue(); 77 if (progress == 100) { 78 downloadBtn.setClickable(true); 79 myTextView.setText("下载完成!"); 80 } else { 81 myTextView.setText("当前进度:" + progress + "%"); 82 } 83 downloadProgressBar.setProgress(progress); 84 } 85 86 }; 87 88 //主下载线程 89 public class downloadTask extends Thread{ 90 private int blockSize, downloadSizeMore; 91 private int threadNum = 5; 92 String urlStr, threadNo, fileName; 93 public downloadTask(String urlStr, int threadNum, String fileName){ 94 this.urlStr = urlStr; 95 this.threadNum = threadNum; 96 this.fileName = fileName; 97 Log.i(TAG,"downloadTask" + fileName); 98 } 99 100 101 @Override 102 public void run() { 103 FileDownloadThread[] fds = new FileDownloadThread[threadNum]; 104 try { 105 URL url = new URL(urlStr); 106 URLConnection conn = url.openConnection(); 107 //获取下载文件的总大小 108 fileSize = conn.getContentLength(); 109 //计算每个线程要下载的数据量 110 blockSize = fileSize / threadNum; 111 downloadSizeMore = (fileSize % threadNum) ; 112 File file = new File(fileName); 113 for(int i = 0; i < threadNum; i++ ) { 114 //启动线程,分别下载自己需要下载的部分 115 116 FileDownloadThread fdt = new FileDownloadThread(url, file, i*blockSize, (i+1)*blockSize - 1); 117 System.out.println("FileDownloadThread---->" + i); 118 Log.i(TAG,"FileDownloadThread---->" + i); 119 fdt.setName("Thread" + i); 120 fdt.start(); 121 fds[i] = fdt; 122 } 123 124 125 boolean finished = false; 126 while(!finished) { 127 // 先把整除的余数搞定 128 downloadedSize = downloadSizeMore; 129 finished = true; 130 for(int i=0; i < fds.length; i++){ 131 downloadedSize += fds[i].getDownloadSize(); 132 if(!fds[i].isFinished()){ 133 finished = false; 134 } 135 136 } 137 handler.sendEmptyMessage(0); 138 sleep(1000); 139 } 140 } catch (MalformedURLException e) { 141 // TODO Auto-generated catch block 142 e.printStackTrace(); 143 } catch (IOException e) { 144 // TODO Auto-generated catch block 145 e.printStackTrace(); 146 } catch (InterruptedException e) { 147 // TODO Auto-generated catch block 148 e.printStackTrace(); 149 } 150 } 151 152 } 153 154 155 @Override 156 public boolean onCreateOptionsMenu(Menu menu) { 157 // Inflate the menu; this adds items to the action bar if it is present. 158 getMenuInflater().inflate(R.menu.main, menu); 159 return true; 160 } 161 162 }
activity_main.xml
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:paddingBottom="@dimen/activity_vertical_margin" 6 android:paddingLeft="@dimen/activity_horizontal_margin" 7 android:paddingRight="@dimen/activity_horizontal_margin" 8 android:paddingTop="@dimen/activity_vertical_margin" 9 tools:context=".MainActivity" 10 android:orientation="vertical" > 11 12 <Button 13 android:layout_width="fill_parent" 14 android:layout_height="wrap_content" 15 android:text="Download" 16 android:id="@+id/downloadButton"/> 17 <ProgressBar 18 android:id="@+id/downloadBar" 19 android:layout_width="200dp" 20 android:layout_height="40dp" 21 style="?android:attr/progressBarStyleHorizontal" 22 android:visibility="gone" 23 android:max="100" 24 android:layout_gravity="center_vertical"/> 25 <TextView 26 android:id="@+id/myTextView" 27 android:layout_width="fill_parent" 28 android:layout_height="wrap_content"/> 29 </LinearLayout>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
posted on 2013-04-18 21:03 Zachary_wiz 阅读(165) 评论(0) 编辑 收藏 举报