package a.a; 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.Activity; import android.os.Bundle; 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.ProgressBar; public class a extends Activity { Button b; OutputStream output;// 輸入出流 ProgressBar bar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b = (Button) findViewById(R.id.btn); bar = (ProgressBar) findViewById(R.id.bar); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { down(); } }); } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); switch(msg.what) { case 0: bar.setVisibility(View.VISIBLE); break; case 1: bar.setProgress(msg.arg1); break; } } }; // 下載方法 必須放在單獨的線程裏 private void down() throws RuntimeException { new Thread(new Runnable() { @Override public void run() { try { Message m = handler.obtainMessage(); m.what = 0; m.sendToTarget(); // 建立URL 寫入下載地址 URL url = new URL("下載路徑"); // 建立HttpURLConnection HttpURLConnection urlcon = (HttpURLConnection) url .openConnection(); //或者上兩句使用URLConnection connection = new URL("下載路徑"). //openConnection(); 下面的urlcon 換成connection // 得到文件大小 long TotalSize = Long.parseLong(urlcon .getHeaderField("Content-Length")); // 得到文件大小 int fileLength = urlcon.getContentLength(); // 得到輸入流 InputStream is = urlcon.getInputStream(); // 建立目錄 File dir = new File("/mnt/sdcard/abc"); dir.mkdir(); // 建立文件 File file = new File("/mnt/sdcard/abc/asd.doc"); // 若是存在則刪除 if(file.exists()) file.delete(); // 建立文件 file.createNewFile(); // 建立文件輸入流 output = new FileOutputStream(file); byte buffer[] = new byte[4 * 1024]; // 已下載 int downsize = 0; while(true) { int down = is.read(buffer); if(down == -1) { break; } downsize += down; output.write(buffer, 0, down); Message m2 = handler.obtainMessage(); m2.what = 1; // 提示已下載百分之多少 m2.arg1 = downsize * 100 / fileLength; m2.sendToTarget(); } // 清除緩存 output.flush(); } catch(Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { // 關閉輸出流 output.close(); } catch(Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); } }所需的權限
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
版權聲明:本文爲博主原創文章,未經博主容許不得轉載。html