android学习笔记3-文件下载

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.INTERNET" >
    </uses-permission>
    <uses-permission android:name="android.permission.WAKE_LOCK" >
    </uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
获得手机的权限,包括网络和读写SD卡的权限
package com.example.testdownfile;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. http://www.open-open.com/lib/view/open1328973152812.html*/
	//private static final String Path="http://p.baidupcs.com/file/8a021c919e4d146226c743ca683b5968?fid=3088732464-250528-651295825860462&time=1401080944&sign=FDTAXER-DCb740ccc5511e5e8fedcff06b081203-%2F6lRviANdxZw7XyJH1NqM2AXTDI%3D&to=pb&fm=N,B,G,e&newver=1&expires=1401081544&rt=sh&r=733120661&logid=1054769191&sh=1&vuk=3088732464&fn=Angelis-Angel.mp3";
	private static final String Path="http://210.30.100.2/Office2010.rar";
	private ProgressBar progressBar;//下载进度条
	private TextView textView;
	private TextView textView2;
	private EditText ipText;
	private Button button;
	private long FileLength;//文件总长度
	private long DownedFileLength=0;
	private InputStream inputStream;
	private URLConnection connection;
	private OutputStream outputStream;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressBar=(ProgressBar) findViewById(R.id.progressBar1);
   
        textView=(TextView) findViewById(R.id.textView1);
        textView2=(TextView) findViewById(R.id.textView2);
        button=(Button) findViewById(R.id.button1);
        button.setOnClickListener(new ButtonListener());
    }
    class ButtonListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			DownedFileLength=0;
			// TODO Auto-generated method stub
		   Thread thread=new Thread(){
			 public void run(){
				 try {
					DownFile(Path);
				} catch (Exception e) {
					// TODO: handle exception
				}
			 }
		   };
		   thread.start();
		}	
    }
    private Handler handler=new Handler()//根据当前已下载文件大小刷新进度条
    {
    	 public void handleMessage(Message msg)
 	    {
		if (!Thread.currentThread().isInterrupted()) {
			switch (msg.what) {
			case 0:
				progressBar.setMax(100);
				textView2.setText("文件大小:"+FileLength/1024/1024+"M");
				Log.i("文件长度----------->", progressBar.getMax()+"");	
				break;
			case 1:
				
				int x=(int) (DownedFileLength*100/FileLength);
				progressBar.setProgress(x);
				System.out.println("x----->"+x);
				textView.setText(x+"%");
				break;
			case 2:
				Toast.makeText(getApplicationContext(), "下载完成", Toast.LENGTH_LONG).show();
				break;
				
			default:
				break;
			}
		}	
		}
    	 
    };

	private void DownFile(String urlString)
    {
    	
		/*
		 * 连接到服务器
		 */
    	
		try {
			 URL url=new URL(urlString);
			 connection=url.openConnection();//打来连接
			 if (connection.getReadTimeout()==5) {
				Log.i("---------->", "当前网络有问题");
				// return;
			   }
			 inputStream=connection.getInputStream();
			
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		/*
		 * 文件的保存路径和和文件名其中Nobody.mp3是在手机SD卡上要保存的路径,如果不存在则新建
		 */
		String savePAth=Environment.getExternalStorageDirectory()+"/download";
		System.out.println("path----->"+savePAth);
		File file1=new File(savePAth);
		if (!file1.exists()) {
	    	file1.mkdir();
		}
		String savePathString=Environment.getExternalStorageDirectory()+"/download"+"/office.rar";
		File file =new File(savePathString);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
		/*
		 * 向SD卡中写入文件,用Handle传递线程
		 */
		Message message=new Message();
		try {
			outputStream=new FileOutputStream(file);
			byte [] buffer=new byte[1024*4];
			FileLength=connection.getContentLength();
			System.out.println("fileLength----->"+FileLength);
			message.what=0;
			handler.sendMessage(message);
			
			while (DownedFileLength<FileLength) {
				outputStream.write(buffer);
			    DownedFileLength+=inputStream.read(buffer);
			    System.out.println("DownedFileLength------>"+DownedFileLength);
			    Log.i("-------->", DownedFileLength+"");
			    Message message1=new Message();
			    message1.what=1;
			    handler.sendMessage(message1);
			}
			Message message2=new Message();
			message2.what=2;
			handler.sendMessage(message2);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
      
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值