Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

實作Android檔案下載進度條:從UI到Handler的完整教學

編輯:關於 Android 開發

在App開發中,檔案下載是非常常見的需求,而如何讓使用者即時掌握下載進度,往往是提升使用體驗的關鍵環節。本文將帶你一步步實作一個具備動態進度顯示的Android下載功能,很適合初學者入門參考。

效果預覽

如圖所示,介面上方是一條藍色進度條,會依據檔案實際下載的百分比逐步填充;中央的文字元件負責顯示目前的完成比例;最下方的ImageView則用來呈現下載完成的圖片。整體目標,就是讓使用者能動態看見下載的即時進度。

核心思路

整個實作可以拆解成三個環節:以背景執行緒負責網路下載、透過Handler在執行緒與UI之間傳遞進度訊息、再由UI更新進度條與文字。由於Android不允許在子執行緒中直接操作介面,因此Handler在這裡扮演了溝通橋樑的角色。

版面配置

版面以RelativeLayout為基礎,上方擺放ProgressBar,中間是顯示百分比的TextView,下方則是負責展示圖片的ImageView。關鍵程式碼如下:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ProgressBar android:id="@+id/progressBar" ... />
    <TextView android:id="@+id/textView" ... />
    <ImageView android:id="@+id/imageView" ... />
</RelativeLayout>

Java程式碼實作

MainActivity中透過Handler接收下載執行緒送來的訊息,並據此更新介面;下載則交由背景執行緒以URLConnection完成。

public class MainActivity extends Activity {
    ProgressBar pb;
    TextView tv;
    ImageView imageView;
    int fileSize;
    int downLoadFileSize;
    String fileEx, fileNa, filename;

    // 用來接收執行緒發送的下載量,進行UI更新
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {
                    case 0:
                        pb.setMax(fileSize);
                    case 1:
                        pb.setProgress(downLoadFileSize);
                        int result = downLoadFileSize * 100 / fileSize;
                        tv.setText(result + "%");
                        break;
                    case 2:
                        Toast.makeText(MainActivity.this, "檔案下載完成", Toast.LENGTH_SHORT).show();
                        FileInputStream fis = null;
                        try {
                            fis = new FileInputStream(Environment.getExternalStorageDirectory()
                                + File.separator + "/ceshi/" + filename);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        Bitmap bitmap = BitmapFactory.decodeStream(fis);
                        imageView.setImageBitmap(bitmap);
                        break;
                    case -1:
                        String error = msg.getData().getString("error");
                        Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();
                        break;
                }
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pb = (ProgressBar)findViewById(R.id.progressBar);
        tv = (TextView)findViewById(R.id.textView);
        imageView = (ImageView) findViewById(R.id.imageView);
        tv.setText("0%");
        new Thread(){
            public void run(){
                try {
                    down_file("https://cdnq.duitang.com/uploads/item/201406/15/20140615203435_ABQMa.jpeg",
                        Environment.getExternalStorageDirectory() + File.separator + "/ceshi/");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    // 檔案下載:url為下載位址,path為本機存放路徑
    public void down_file(String url, String path) throws IOException {
        filename = url.substring(url.lastIndexOf("/") + 1);
        URL myURL = new URL(url);
        URLConnection conn = myURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        this.fileSize = conn.getContentLength(); // 依響應取得檔案大小
        if (this.fileSize <= 0) throw new RuntimeException("無法得知檔案大小");
        if (is == null) throw new RuntimeException("stream is null");
        File file1 = new File(path);
        File file2 = new File(path + filename);
        if (!file1.exists()) file1.mkdirs();
        if (!file2.exists()) file2.createNewFile();
        FileOutputStream fos = new FileOutputStream(path + filename);
        byte buf[] = new byte[1024];
        downLoadFileSize = 0;
        sendMsg(0);
        do {
            int numread = is.read(buf);
            if (numread == -1) break;
            fos.write(buf, 0, numread);
            downLoadFileSize += numread;
            sendMsg(1); // 更新進度條
        } while (true);
        sendMsg(2); // 通知下載完成
        try { is.close(); } catch (Exception ex) {
            Log.e("tag", "error: " + ex.getMessage(), ex);
        }
    }

    // 由執行緒向Handler發送下載量,以更新UI
    private void sendMsg(int flag) {
        Message msg = new Message();
        msg.what = flag;
        handler.sendMessage(msg);
    }
}

別忘了網路權限

最後務必在AndroidManifest.xml中加入網路存取權限,否則程式會在執行時抛出異常:

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

至此,一個能動態顯示下載進度的Android小範例就完成了。理解了「背景執行緒下載、Handler溝通、UI更新」這條主線之後,你就能把它套用到更多需要下載與進度回饋的場景中。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved