AsyncTask下载文件

package com.example.asyncdemo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private Button bt_download;
	private ProgressBar progressBar;
	private TextView tv_progress;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		bt_download = (Button) this.findViewById(R.id.bt_download);
		progressBar = (ProgressBar) this.findViewById(R.id.progress_bar);
		tv_progress = (TextView) this.findViewById(R.id.textview_progress);
		
		bt_download.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				new DownloadThread().execute("http://www.winrar.com.cn/download/wrar380sc.exe");
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	
	public class DownloadThread extends AsyncTask<String, Integer, Void>{
		private long fileSize; //文件总大小
		private long completeSize; //已下载文件大小
		
		@Override
		protected Void doInBackground(String... params) {
			InputStream in = null;
			OutputStream out = null;
			String downloadUrl = params[0];
			try {
				URL url = new URL(downloadUrl);
				
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(5000);
				fileSize = conn.getContentLength();
				
				if(conn.getResponseCode() == 200){
					in = conn.getInputStream();
					
					//判断是否存在SD卡
					if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
						Toast.makeText(getApplicationContext(), "SD卡不存在", Toast.LENGTH_LONG).show();
						return null;
					}
					String savePath = Environment.getExternalStorageDirectory().getAbsolutePath();
					String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/")+1);
					savePath += "/" + fileName;
					
					out = new FileOutputStream(new File(savePath));
					int len = 0;
					byte[] buffer = new byte[1024];
					while((len = in.read(buffer)) != -1){
						out.write(buffer, 0, len);
						completeSize += len;
						//下载进度
						int progress = (int) (completeSize * 100 / fileSize);
						this.publishProgress(progress);
					}
				}
			} catch (MalformedURLException e) {	
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try {
					if(in != null){
						in.close();
					}
					if(out != null){
						out.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			Log.i("progress", String.valueOf(values[0]));
			progressBar.setProgress(values[0]);
			tv_progress.setText(values[0]+"%");
			if(values[0] >= 100){
				tv_progress.setText("下载完成");
			}
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值