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

來源:互聯網
上載者:User
這裡小結下,如何用android的模擬器去建立一個sdcard,並且學習如何在android中去下載

一個網上的檔案,儲存到android,並且下載時,會顯示一個進度條

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

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

   android:orientation="vertical"

   android:layout_width="fill_parent"

   android:layout_height="fill_parent"

   >

<TextView 

   android:layout_width="fill_parent"

   android:layout_height="wrap_content"

   android:text="@string/hello"

   />

<Button

    android:text="Start long running task.."

    android:id="@+id/startBtn"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content">

</Button>

</LinearLayout>

2 主程式

   package com.liao;

import java.io.BufferedInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.URL;

import java.net.URLConnection;

import android.app.Activity;

import android.app.Dialog;

import android.app.ProgressDialog;

import android.os.AsyncTask;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class AndroAsync extends Activity {

public static final int DIALOG_DOWNLOAD_PROGRESS = 0;

    private Button startBtn;

    private ProgressDialog mProgressDialog;

   

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        startBtn = (Button)findViewById(R.id.startBtn);

        startBtn.setOnClickListener(new OnClickListener(){

            public void onClick(View v) {

                startDownload();

            }

        });

    }

    private void startDownload() {

        String url = "http://image-

7.verycd.com/0d7596f5db7df1742236466dc91311b1435702(120x120)/thumb.jpg";

        new DownloadFileAsync().execute(url);

    }

    @Override

    protected Dialog onCreateDialog(int id) {

        switch (id) {

            case DIALOG_DOWNLOAD_PROGRESS:

                mProgressDialog = new ProgressDialog(this);

                mProgressDialog.setMessage("Downloading file..");

                mProgressDialog.setProgressStyle

(ProgressDialog.STYLE_HORIZONTAL);

                mProgressDialog.setCancelable(false);

                mProgressDialog.show();

                return mProgressDialog;

            default:

                return null;

        }

    }

    class DownloadFileAsync extends AsyncTask<String, String, String> {

       

        @Override

        protected void onPreExecute() {

            super.onPreExecute();

            showDialog(DIALOG_DOWNLOAD_PROGRESS);

        }

        @Override

        protected String doInBackground(String... aurl) {

            int count;

            try {

                URL url = new URL(aurl[0]);

                URLConnection conexion = url.openConnection();

                conexion.connect();

                int lenghtOfFile = conexion.getContentLength();

                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

                InputStream input = new BufferedInputStream(url.openStream());

                OutputStream output = new FileOutputStream

("/sdcard/picture.jpg");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {

                    total += count;

                    publishProgress(""+(int)((total*100)/lenghtOfFile));

                    output.write(data, 0, count);

                }

                output.flush();

                output.close();

                input.close();

            } catch (Exception e) {

           

            Log.e("error",e.getMessage().toString());

            System.out.println(e.getMessage().toString());

            }

            return null;

        }

        protected void onProgressUpdate(String... progress) {

             Log.d("ANDRO_ASYNC",progress[0]);

             mProgressDialog.setProgress(Integer.parseInt(progress[0]));

        }

        @Override

        protected void onPostExecute(String unused) {

            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);

        }

    }

}

  注意這裡,在startdownload 方法中,調用了DownloadFileAsync內部類,這個內部類充

分利用了AsyncTask的非同步工作特性,是很方便的,其中注意doInBackground(這個階段下

載圖片),onProgressUpdate是讓進度條完成後消失。

最後,要記得在androidmanifest.xml中的</application>後加入

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

讓能有訪問互連網的能力

3 下面講解下其中如何用到的,把圖片儲存到sdcard中去,由於是模擬器,因此

只能在磁碟上類比一個IMG檔案來充當類比,步驟如下:

  1) 開啟cmd,進入Android SDK安裝路徑下的tools目錄下,輸入如下命令:

mksdcard 1024M sdcard.img

該命令會在目前的目錄下產生一個sdcard.img檔案,該檔案是Android模擬器的SD卡鏡像檔案

。1024M表示SD卡有1024M大小,即1G容量。目前Android支援8M~128G的SD卡。

 

  2) 運行帶sdcard的模擬器

    A 在cmd中啟動帶有sdcard的模擬器

進入Android SDK安裝路徑下的tools目錄中,運行下面命令:

emulator -avd name_avd -sdcard sdcard.img

其中,name_avd是已有的模擬器的名字,sdcard.img是第一步建立的SD卡鏡像檔案。

    B  在eclipse中,建立模擬器的時候,指定SD卡鏡像檔案的路徑,並且加入對SD卡的支援選項

開啟eclipse,進入:window->android SDK and AVD manager,

然後在create avd的時候,在SD CARD中選擇"FILE",然後再選擇sd support;

3)如何看SDCARD中的檔案

  1)在cmd中,進入Android SDK的安裝路徑下的tools目錄中,運行命令:

adb push E:\abc.jpg sdcard/abc.jpg

其中,E:\test.3gp 是本地要上傳的檔案,sdcard/abc.jpg 為上傳到SD卡中的路徑。

注意:adb push 電腦路徑 模擬器路徑

在電腦路徑中,必須使用“\”,在模擬器路徑中必須使用“/”,並且模擬器的根路徑是只

讀的。

2 ) 在eclipse環境中

在設定了RUN的命令參數後,RUN一個應用程式,然後使用DDMS的File Explorer工具匯入匯出文

件。開啟DDMS工具,在eclipse的windows->Open Perspective->Other...裡面開啟DDMS工具,在

DDMS工具的File Explorer標籤裡面選擇sdcard目錄匯入匯出檔案,

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.