package
lizhen.download;
import
java.io.File;
import
java.io.FileOutputStream;
import
java.io.IOException;
import
java.io.InputStream;
import
org.apache.http.HttpEntity;
import
org.apache.http.HttpResponse;
import
org.apache.http.HttpStatus;
import
org.apache.http.client.ClientProtocolException;
import
org.apache.http.client.HttpClient;
import
org.apache.http.client.methods.HttpGet;
import
org.apache.http.impl.client.DefaultHttpClient;
import
android.os.AsyncTask;
public
class
DownloadAsyncTask
extends
AsyncTask<String, Integer, Boolean> {
protected
int
size;
protected
String errorMessage;
@Override
protected
Boolean doInBackground(String... params) {
String url = params[
0
];
String path = params[
1
];
try
{
InputStream source = requestInputStream(url);
/**
* 创建文件写入数据,并更新进度
*/
fileWrite(source, path,
new
OnProgressUpdateListener() {
@Override
public
void
onProgressUpdate(
int
progress) {
publishProgress(progress);
}
});
}
catch
(ClientProtocolException e) {
errorMessage = e.getMessage();
cancel(
true
);
return
false
;
}
catch
(IOException e) {
errorMessage = e.getMessage();
cancel(
true
);
return
false
;
}
return
true
;
}
/**
* 文件写入
*
* @param in
* 数据源输出流
* @param path
* 文件路径
* @param listener
* 下载进度监听器
* */
private
void
fileWrite(InputStream in, String path,
OnProgressUpdateListener listener)
throws
IOException {
File file = createFile(path);
FileOutputStream fileOutputStream =
new
FileOutputStream(file);
byte
buffer[] =
new
byte
[
1024
];
int
progress =
0
;
int
readBytes =
0
;
while
((readBytes = in.read(buffer)) != -
1
) {
progress += readBytes;
fileOutputStream.write(buffer,
0
, readBytes);
if
(listener !=
null
) {
listener.onProgressUpdate(progress);
}
}
in.close();
fileOutputStream.close();
}
/**
* 下载进度监听器
* */
private
interface
OnProgressUpdateListener {
/**
* 下载进度更新
*
* @param progress
* 进度
* */
public
void
onProgressUpdate(
int
progress);
}
/**
* 根据资源URL地址取得资源输入流
*
* @param url
* URL地址
* @return 资源输入流
* @throws ClientProtocolException
* @throws IOException
* */
private
InputStream requestInputStream(String url)
throws
ClientProtocolException, IOException {
InputStream result =
null
;
HttpGet httpGet =
new
HttpGet(url);
HttpClient httpClient =
new
DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
int
httpStatusCode = httpResponse.getStatusLine().getStatusCode();
if
(httpStatusCode == HttpStatus.SC_OK) {
HttpEntity httpEntity = httpResponse.getEntity();
size = (
int
) httpEntity.getContentLength();
result = httpEntity.getContent();
}
return
result;
}
/**
* 根据文件路径创建文件
*
* @param path
* 文件路径
* @return 文件File实例
* @return IOException
* */
private
File createFile(String path)
throws
IOException {
File file =
new
File(path);
file.createNewFile();
return
file;
}
/**
* 返回错误信息
*
* @return 错误信息
* */
public
String getErrorString() {
return
this
.errorMessage;
}
}