上次基本上已经把AsyncTask的知识点已经讲清楚啦。这次就是再用一个例子来增加自己的理解。这里还可以知道HttpURLConnection的用法。
布局:android_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="cn.edu.huse.daywork2.MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="download"
android:text="下载文件" />
</RelativeLayout>
MainActivity.java
package cn.edu.huse.daywork2;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import cn.edu.huse.daywork2.domain.DownloadFileUtil;
import cn.edu.huse.daywork2.domain.DownloadFileUtil.OnDownloadFileCompleteListener;
public class MainActivity extends Activity {
private final String URL = "http://sj.img4399.com/game_list/47/com.wepie.snake/wepie.snake.v117518.apk?ref=news";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void download(View v){
DownloadFileUtil dfu = new DownloadFileUtil(this);
dfu.DownloadFile(URL, "zql.apk", new OnDownloadFileCompleteListener() {
@Override
public void OnDownloadFileComplete(File file) {
if(file != null){
Toast.makeText(MainActivity.this, "下载成功:"+file.getAbsolutePath(), 0).show();
}else{
Toast.makeText(MainActivity.this, "下载失败", 0).show();
}
}
});
}
}
DownloadFileUtil.java
package cn.edu.huse.daywork2.domain;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
public class DownloadFileUtil {
//得到sdcard的路径
private final String DIR = Environment.getExternalStorageDirectory().getAbsolutePath();
//判断sdcard是否存在
private String state = Environment.getExternalStorageState();
//上下文
private Context context;
//构造函数,传递上下文
public DownloadFileUtil(Context context) {
super();
this.context = context;
}
//回调接口
public interface OnDownloadFileCompleteListener{
void OnDownloadFileComplete(File file);
}
private OnDownloadFileCompleteListener mListener;
public void DownloadFile(String url, String fileName, OnDownloadFileCompleteListener listener){
this.mListener = listener;
//启动异步任务
new DownloadTast().execute(url,fileName);
}
private class DownloadTast extends AsyncTask<String,Integer,File>{
private ProgressDialog mDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(context);
//不确定进度条设为水平的
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setTitle("正在下载中");
//最大值为100
mDialog.setMax(100);
//显示进度条
mDialog.show();
}
@Override
protected File doInBackground(String... params) {
if(state.equals(Environment.MEDIA_MOUNTED)){
try {
//创建文件 params[1] 文件名
File file = new File(DIR,params[1]);
OutputStream outputStream = new FileOutputStream(file);
//创建URL
URL url = new URL(params[0]);
//获得连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//获得输入流
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
//要下载文件的总长度
int length = conn.getContentLength();
//已下载的长度
int downLen = 0;
//读取文件
while((len = inputStream.read(buffer))!=-1){
outputStream.write(buffer, 0, len);
downLen += len;
int progress = (int) (1.0*downLen/length*100);
mDialog.setProgress(progress);
}
return file;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(File result) {
super.onPostExecute(result);
mDialog.dismiss();
//接口回调
if(mListener != null){
mListener.OnDownloadFileComplete(result);
}
}
}
}
添加权限
运行结果: