Android-マルチスレッドダウンロード
17429 ワード
マルチスレッドダウンロード機能を実現し、コードは以下の通りです.
ファイルダウンロードクラスを新規作成します.java
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.amos.download.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainApp extends Activity implements OnClickListener {
private static final String TAG = MainApp.class.getSimpleName();
/** TextView */
private TextView mMessageView;
/** ProgressBar */
private ProgressBar mProgressbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_activity);
findViewById(R.id.download_btn).setOnClickListener(this);
mMessageView = (TextView) findViewById(R.id.download_message);
mProgressbar = (ProgressBar) findViewById(R.id.download_progress);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.download_btn) {
doDownload();
}
}
/**
* Handler UI
*/
@SuppressLint("HandlerLeak")
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mProgressbar.setProgress(msg.getData().getInt("size"));
float temp = (float) mProgressbar.getProgress()
/ (float) mProgressbar.getMax();
int progress = (int) (temp * 100);
if (progress == 100) {
Toast.makeText(MainApp.this, " !", Toast.LENGTH_LONG).show();
}
mMessageView.setText(" :" + progress + " %");
}
};
/**
* , SD 、
*/
private void doDownload() {
// SD
String path = Environment.getExternalStorageDirectory()
+ "/amosdownload/";
File file = new File(path);
// SD
if (!file.exists()) {
file.mkdir();
}
// progressBar
mProgressbar.setProgress(0);
// , URL , HttpHeader
String downloadUrl = "http://gdown.baidu.com/data/wisegame/91319a5a1dfae322/baidu_16785426.apk";
String fileName = "baidu_16785426.apk";
int threadNum = 5;
String filepath = path + fileName;
Log.d(TAG, "download file path:" + filepath);
downloadTask task = new downloadTask(downloadUrl, threadNum, filepath);
task.start();
}
/**
*
*/
class downloadTask extends Thread {
private String downloadUrl;//
private int threadNum;//
private String filePath;//
private int blockSize;//
public downloadTask(String downloadUrl, int threadNum, String fileptah) {
this.downloadUrl = downloadUrl;
this.threadNum = threadNum;
this.filePath = fileptah;
}
@Override
public void run() {
FileDownloadThread[] threads = new FileDownloadThread[threadNum];
try {
URL url = new URL(downloadUrl);
Log.d(TAG, "download file http path:" + downloadUrl);
URLConnection conn = url.openConnection();
//
int fileSize = conn.getContentLength();
if (fileSize <= 0) {
System.out.println(" ");
return;
}
// ProgressBar Size
mProgressbar.setMax(fileSize);
//
blockSize = (fileSize % threadNum) == 0 ? fileSize / threadNum
: fileSize / threadNum + 1;
Log.d(TAG, "fileSize:" + fileSize + " blockSize:");
File file = new File(filePath);
for (int i = 0; i < threads.length; i++) {
// ,
threads[i] = new FileDownloadThread(url, file, blockSize,
(i + 1));
threads[i].setName("Thread:" + i);
threads[i].start();
}
boolean isfinished = false;
int downloadedAllSize = 0;
while (!isfinished) {
isfinished = true;
//
downloadedAllSize = 0;
for (int i = 0; i < threads.length; i++) {
downloadedAllSize += threads[i].getDownloadLength();
if (!threads[i].isCompleted()) {
isfinished = false;
}
}
// handler
Message msg = new Message();
msg.getData().putInt("size", downloadedAllSize);
mHandler.sendMessage(msg);
// Log.d(TAG, "current downloadSize:" + downloadedAllSize);
Thread.sleep(1000);// 1
}
Log.d(TAG, " all of downloadSize:" + downloadedAllSize);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
ファイルダウンロードクラスを新規作成します.java
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URL;
import java.net.URLConnection;
import android.util.Log;
public class FileDownloadThread extends Thread {
private static final String TAG = FileDownloadThread.class.getSimpleName();
/** */
private boolean isCompleted = false;
/** */
private int downloadLength = 0;
/** */
private File file;
/** */
private URL downloadUrl;
/** ID */
private int threadId;
/** */
private int blockSize;
/**
*
* @param url:
* @param file:
* @param blocksize:
* @param threadId: ID
*/
public FileDownloadThread(URL downloadUrl, File file, int blocksize,
int threadId) {
this.downloadUrl = downloadUrl;
this.file = file;
this.threadId = threadId;
this.blockSize = blocksize;
}
@Override
public void run() {
BufferedInputStream bis = null;
RandomAccessFile raf = null;
try {
URLConnection conn = downloadUrl.openConnection();
conn.setAllowUserInteraction(true);
int startPos = blockSize * (threadId - 1);//
int endPos = blockSize * threadId - 1;//
// 、
conn.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos);
System.out.println(Thread.currentThread().getName() + " bytes="
+ startPos + "-" + endPos);
byte[] buffer = new byte[1024];
bis = new BufferedInputStream(conn.getInputStream());
raf = new RandomAccessFile(file, "rwd");
raf.seek(startPos);
int len;
while ((len = bis.read(buffer, 0, 1024)) != -1) {
raf.write(buffer, 0, len);
downloadLength += len;
}
isCompleted = true;
Log.d(TAG, "current thread task has finished,all size:"
+ downloadLength);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
*
*/
public boolean isCompleted() {
return isCompleted;
}
/**
*
*/
public int getDownloadLength() {
return downloadLength;
}
}