android AsyncTask下载文件并且显示进度

第一步:在AndroidManifest.xml文件中添加需要的权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

第二步:简单的布局文件:

<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=".MainActivity" >

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/hello_world"
        android:textSize="16dp" />
    <Button 
        android:id="@+id/button_load"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下载"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        />

</RelativeLayout>

第三步:上菜:

public class MainActivity extends Activity {

	public static final String TAG	= "MainActivity";
	
	Button button;
	TextView textView;
	
	private String url = "http://192.168.1.105:8080/MagazineAR/data/20130528093734/1369705054180.3gp";
	
	private class LoadFileTask extends AsyncTask<Void, Integer, Integer>{
		//需要下载文件的url
		private String fileUrl;
		//需要保存的本地路径
		private String location;
		
		public LoadFileTask(String fileUrl, String location){
			textView.setText("开始下载:");
			this.fileUrl 	= fileUrl;
			this.location	= location;
		}
		
		@Override
		protected Integer doInBackground(Void... params) {
			Log.e(TAG, "doInBackground----begin");
			if (fileUrl == null || fileUrl.equals("") || location == null || location.equals(""))
				return -1;
			
			float totalLength = 0f;
			float sum = 0f;
			FileOutputStream fos = null;
			InputStream is = null;
			BufferedInputStream bis = null;
			
				try {
					
					URL url = new URL(fileUrl);
					HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
					conn.setConnectTimeout(5000);
					totalLength = conn.getContentLength();
					
					File file = new File(location);
					fos = new FileOutputStream(file);
					
					is = conn.getInputStream();
					bis = new BufferedInputStream(is);
					byte[] buffer = new byte[1024 * 1024];
					int len ;
					
					while( ( len = bis.read(buffer)) != -1 ){
						fos.write(buffer, 0, len);
						sum += len;
						
						//更新下载进度
						publishProgress((int)((sum / totalLength) * 100));
					}
					
					
				} catch (MalformedURLException e) {
					e.printStackTrace();
					return -1;
					
				} catch (IOException e) {
					e.printStackTrace();
					return -1;
					
				}finally{
					try {
						if (fos != null){
							fos.close();
						}
						if (bis != null){
							bis.close();
						}
						if (is != null){
							is.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
			Log.e(TAG, "doInBackground----end");
			return (int)totalLength;
		}

		@Override
		protected void onCancelled() {
			Log.e(TAG, "onCancelled");
			super.onCancelled();
		}


		@Override
		protected void onPostExecute(Integer result) {
			Log.e(TAG, "onPostExecute");
			
			textView.setText("下载结束,总共长度是:" + result);
			
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			Log.e(TAG, "onPreExecute");
			
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			Log.e(TAG, "onProgressUpdate");
			
			textView.setText("进度:" + values[0] + " %");
			
			super.onProgressUpdate(values);
		}
		
	}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        button = (Button) findViewById(R.id.button_load);
        textView = (TextView) findViewById(R.id.textview);
        
        button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
					LoadFileTask loadFileTask = new LoadFileTask(url, 
						 Environment.getExternalStorageDirectory().getPath() + "/testmusicfile.3gp" /*"/mnt/sdcard/testmusicfile.3gp"*/);
					loadFileTask.execute();
				}
			}
		});
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值