Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android DownloadManager 使用教學:下載、查詢進度與刪除

Android 3.2 起提供了 DownloadManager,讓下載任務交給系統代管,還能顯示通知列進度。以下用一個完整例子說明如何啟動下載、輪詢進度以及移除任務。

版面配置

放三個按鈕(開始下載、查詢狀態、刪除下載)與兩個 TextView(顯示檔案總大小與已下載大小):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
        android:id="@+id/start"
        android:text="Start Download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="startDownload"
    />
    <Button
        android:id="@+id/query"
        android:text="Query Status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="queryDownloadStatus"
    />
    <Button
        android:id="@+id/del"
        android:text="del download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="delDownloads"
    />

    <TextView  android:id="@+id/tvsize"
        android:text="file"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView  android:id="@+id/tvinfo"
        android:text="file"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

Java 程式

package com.download;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
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.widget.TextView;
import android.widget.Toast;

public class DWManagerThread extends Activity {

    private DownloadManager mgr = null;
    private long lastDownload = -1L;

    TextView tvdwsize ;
    TextView tvdwinfo = null;

    private String strUrl = "https://dl.google.com/android/ndk/android-ndk-r6-linux-x86.tar.bz2";
    public static final int MSG_DWPACKSIZE = 1;
    public static final int MSG_DWSIZE = 2;

    Handler handler = new Handler(){
        public void handleMessage (Message msg) {
            switch(msg.what){
                case MSG_DWPACKSIZE:
                    String  size = String.valueOf(msg.arg1);
                    tvdwinfo.setText(size);
                    Log.d("handleMessage", "dwpacksize="+size);
                    break;
                case MSG_DWSIZE:
                    String dwsize = String.valueOf(msg.arg1);
                    tvdwsize.setText(dwsize);
                    Log.d("handleMessage", "dwsize="+dwsize);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tvdwsize = (TextView)findViewById(R.id.tvsize);
        tvdwinfo = (TextView)findViewById(R.id.tvinfo);

        mgr = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
    }

    public void startDownload(View v) {
        Uri uri = Uri.parse(strUrl);

        Environment
            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .mkdirs();

        Request dwreq = new DownloadManager.Request(uri);

        dwreq.setTitle("Demo");
        dwreq.setDescription("android-ndk-r6-linux-x86.tar.bz2");
        dwreq.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"android-ndk-r6-linux-x86.tar.bz2");
        dwreq.setNotificationVisibility(0);
        dwreq.setShowRunningNotification(true);

        lastDownload = mgr.enqueue(dwreq);
    }

    public void queryDownloadStatus(View v)  {

        Runnable queryRunable = new Runnable() {
            long totalsize = 0;
            long dowsize = 0;
            boolean downok = false;
            Cursor c = null;

            public void run() {

                //查詢下載文件總大小
                totalsize = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

                Message msg_packsize = new Message();
                msg_packsize.what = MSG_DWPACKSIZE;
                msg_packsize.arg1 = (int) totalsize;
                handler.sendMessage (msg_packsize);

                while (downok == false) {
                    c = mgr.query(new DownloadManager.Query().setFilterById(lastDownload));

                    if (c == null) {
                    } else {
                        c.moveToFirst();
                        //查詢已經下載的大小
                        dowsize = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                        if (totalsize == dowsize) downok = true;
                    }

                    Message msg = new Message();
                    msg.what = MSG_DWSIZE;
                    msg.arg1 = (int) dowsize;
                    handler.sendMessage (msg);

                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    c.close();
                }
            }//run
        };

        Thread background = new Thread(queryRunable);
        background.start();
    }

    public void delDownloads(View view) {

        Toast.makeText(this, "delDownloads", Toast.LENGTH_LONG).show();
        mgr.remove(lastDownload);

    }

    //查看下載窗口
    public void viewDownWindow(View v) {
        startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
    }

}

幾個關鍵 API

  • mgr.enqueue(request):把任務丟進佇列,回傳的 long 就是下載 ID,後續查詢與刪除都靠它。
  • setDestinationInExternalPublicDir:指定存放位置,這裡用系統的 Downloads 公共目錄。
  • DownloadManager.Query().setFilterById(id):只查詢指定任務,再用 COLUMN_TOTAL_SIZE_BYTES 與 COLUMN_BYTES_DOWNLOADED_SO_FAR 兩欄算出進度。
  • ACTION_VIEW_DOWNLOADS:直接開啟系統的下載管理介面。

要提醒的是,範例中的查詢寫在背景 Thread 裡,但 c 在 run() 內第一次被使用前尚未初始化,實際執行會出現空指標錯誤,記得先 mgr.query(...) 取得 Cursor 再讀欄位;另外 Message.arg1 是 int,大檔的位元組數會溢位,正式版本請改用 long 承載並搭配 msg.what 以外的傳遞方式。别忘了在 manifest 加上 android.permission.INTERNET 與 WRITE_EXTERNAL_STORAGE。

Copyright © Linux教程網 All Rights Reserved