AsyncTask下载大文件并可以取消异步任务




public class MainActivity extends Activity {
private Button download;
/* SD卡根目录 */
private File rootDie;
/* 输出文件名称 */
private String outFileName = "呱虎.apk";
/* 进度条对话框 */
private ProgressDialog pdialog;
private MyLoadAsyncTask task;
private boolean falg=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkAndCreateDir();

pdialog = new ProgressDialog(this);
/* 进度条对话框属性设置 */
pdialog.setMessage("正在下载中...");
pdialog.setTitle("提示信息");
/* 进度值最大100 */
pdialog.setMax(100);
/* 水平风格进度条 */
pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
/* 无限循环模式 */
pdialog.setIndeterminate(false);
/* 可取消 */
pdialog.setCancelable(false);


pdialog.setButton("暂停",new DialogInterface.OnClickListener() {  
             
           @Override  
           public void onClick(DialogInterface dialog, int which) {  
               //删除消息队列  
//                handler.removeMessages(PRO);  
                 
           }  
       });  
         
pdialog.setButton2("取消",new DialogInterface.OnClickListener() {  
             
           @Override  
           public void onClick(DialogInterface dialog, int which) {  
            if (task != null && task.getStatus() == AsyncTask.Status.RUNNING) {
            falg=true;
            task.cancel(true);
            File file=new File(rootDie + "/downloads/", outFileName);
            if(file.exists()){
           
            file.delete();
            }
            }        
           }  
       });  


download=(Button) this.findViewById(R.id.download);
download.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {

/* 异步下载 */
task= new MyLoadAsyncTask();
task.execute("http://ttl6.pc6.com/lff/NetbankClient.zip");
}
});
}



/* 检查sdcard并创建目录文件 */
private void checkAndCreateDir() {
/* 获取sdcard目录 */
rootDie = Environment.getExternalStorageDirectory();

/* 新文件的目录 */
File newFile = new File(rootDie + "/downloads/");
if (!newFile.exists()) {
/* 如果文件不存在就创建目录 */
newFile.mkdirs();
}
}


/* 异步任务,后台处理与更新UI */
class MyLoadAsyncTask extends AsyncTask<String, Integer, String> {
/* 后台线程 */
@Override
protected String doInBackground(String... params) {
/* 所下载文件的URL */
try {
URL url = new URL(params[0]);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// URL属性设置 
conn.setRequestMethod("GET");
// URL建立连接 
conn.connect();
/* 下载文件的大小 */
int fileOfLength = conn.getContentLength();
// Toast.makeText(MainActivity.this, "fileOfLength=="+fileOfLength, 1).show();
/* 每次下载的大小与总下载的大小 */
int totallength = 0;
int length = 0;
/* 输入流 */
InputStream in = conn.getInputStream();
/* 输出流 */
FileOutputStream out = new FileOutputStream(new File(rootDie + "/downloads/", outFileName));
/* 缓存模式,下载文件 */
byte[] buff = new byte[1024 * 1024];
while ((length = in.read(buff)) > 0) {
if(isCancelled()) return null;
totallength += length;
int str1 = (int)((double)totallength / fileOfLength * 100);//先计算出百分比在转换成整型
 publishProgress(str1,totallength,fileOfLength);
out.write(buff, 0, length);
}
/* 关闭输入输出流 */
in.close();
out.flush();
out.close();




} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}




/* 预处理UI线程 */
@Override
protected void onPreExecute() {

super.onPreExecute();
/* 显示对话框 */
pdialog.show();
}




/* 结束时的UI线程 */
@Override
protected void onPostExecute(String result) {

super.onPostExecute(result);
pdialog.dismiss();
}




/* 处理UI线程,会被多次调用,触发事件为publicProgress方法 */
@Override
protected void onProgressUpdate(Integer... values) {
if(isCancelled()) return;
 pdialog.setMessage(String.format("已读%d M, 共%d M",//字节为单位
                  values[1] / 1024 / 1024, values[2] / 1024 / 1024));//将values[1]赋给第一个%d,第二个同理
/* 进度显示 */
pdialog.setProgress(values[0]);
}




}



}



源码下载地址:http://download.csdn.net/detail/sinat_28238111/9750735

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值