天天看點

Android 中下載下傳檔案到sdcard和進度條小結

這裡小結下,如何用android的模拟器去建立一個sdcard,并且學習如何在android中去下載下傳一個網上的檔案,儲存到android,并且下 載時,會顯示一個進度條.上述講的就是我們這一篇代碼要實作的内容。這篇内容其實是很重要的,大家可要好好的看了哦。

 

1 頁面結構,提供一個button,點BUTTON時,去下載下傳一個圖檔,main.xml設計如下:

Java代碼:

  1. < ?xml version="1.0" encoding="utf-8"?>
  2. < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. < TextView
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:text="@string/hello"
  11. />
  12. < Button
  13. android:text="Start long running task.."
  14. android:id="@+id/startBtn"
  15. android:layout_width="fill_parent"
  16. android:layout_height="wrap_content">
  17. < /Button>
  18. < /LinearLayout>

複制代碼

2 主程式

Java代碼:

  1. package eoe.liao;
  2. import java.io.BufferedInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8. import android.app.Activity;
  9. import android.app.Dialog;
  10. import android.app.ProgressDialog;
  11. import android.os.AsyncTask;
  12. import android.os.Bundle;
  13. import android.util.Log;
  14. import android.view.View;
  15. import android.view.View.OnClickListener;
  16. import android.widget.Button;
  17. public class AndroAsync extends Activity {
  18. public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
  19. private Button startBtn;
  20. private ProgressDialog mProgressDialog;
  21. @Override
  22. public void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.main);
  25. startBtn = (Button)findViewById(R.id.startBtn);
  26. startBtn.setOnClickListener(new OnClickListener(){
  27. public void onClick(View v) {
  28. startDownload();
  29. }
  30. });
  31. }
  32. private void startDownload() {
  33. String url = "http://image-7.verycd.com/0d7596f5db7df1742236466dc91311b1435702(120x120)/thumb.jpg";
  34. new DownloadFileAsync().execute(url);
  35. }
  36. @Override
  37. protected Dialog onCreateDialog(int id) {
  38. switch (id) {
  39. case DIALOG_DOWNLOAD_PROGRESS:
  40. mProgressDialog = new ProgressDialog(this);
  41. mProgressDialog.setMessage("Downloading file..");
  42. mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  43. mProgressDialog.setCancelable(false);
  44. mProgressDialog.show();
  45. return mProgressDialog;
  46. default:
  47. return null;
  48. }
  49. }
  50. class DownloadFileAsync extends AsyncTask< String, String, String> {
  51. @Override
  52. protected void onPreExecute() {
  53. super.onPreExecute();
  54. showDialog(DIALOG_DOWNLOAD_PROGRESS);
  55. }
  56. @Override
  57. protected String doInBackground(String... aurl) {
  58. int count;
  59. try {
  60. URL url = new URL(aurl[0]);
  61. URLConnection conexion = url.openConnection();
  62. conexion.connect();
  63. int lenghtOfFile = conexion.getContentLength();
  64. Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
  65. InputStream input = new BufferedInputStream(url.openStream());
  66. OutputStream output = new FileOutputStream("/sdcard/picture.jpg");
  67. byte data[] = new byte[1024];
  68. long total = 0;
  69. while ((count = input.read(data)) != -1) {
  70. total += count;
  71. publishProgress(""+(int)((total*100)/lenghtOfFile));
  72. output.write(data, 0, count);
  73. }
  74. output.flush();
  75. output.close();
  76. input.close();
  77. } catch (Exception e) {
  78. Log.e("error",e.getMessage().toString());
  79. System.out.println(e.getMessage().toString());
  80. }
  81. return null;
  82. }
  83. protected void onProgressUpdate(String... progress) {
  84. Log.d("ANDRO_ASYNC",progress[0]);
  85. mProgressDialog.setProgress(Integer.parseInt(progress[0]));
  86. }
  87. @Override
  88. protected void onPostExecute(String unused) {
  89. dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
  90. }
  91. }
  92. }

複制代碼

注意這裡,在startdownload 方法中,調用了DownloadFileAsync内部類,這個内部類充分利用了AsyncTask的異步工作特性,是很友善 的,onProgressUpdate是讓進度條完成後消失。最後,要記得在androidmanifest.xml中的< /application>後加入< uses-permission android:name="android.permission.INTERNET" />讓能有通路網際網路的能力.