Android開發(fā)(22)使用DownloadManager下載文件

概述

使用DownloadManager 是個(gè)很好用的下載方式醒颖。它會(huì)出現(xiàn)在任務(wù)欄,指示當(dāng)前的下載位置壳炎。它使用廣播來接收完成消息泞歉,點(diǎn)擊任務(wù)事件的交互逼侦。

實(shí)現(xiàn)步驟

1.添加權(quán)限

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

2.在頁面里初始化

  DownloadManager downloadManager;
  
  // 過SystemService 以獲取 DownloadManager
         downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

3.啟動(dòng)下載

    Request request = new Request(
    Uri.parse("http://192.168.3.123:8080/androidautoupdate/apks/2.zip"));
    
    request.setAllowedNetworkTypes(
    DownloadManager.Request.NETWORK_MOBILE
    | DownloadManager.Request.NETWORK_WIFI)
    .setAllowedOverRoaming(false) // 缺省是true
    .setTitle("更新") // 用于信息查看
    .setDescription("下載apk") // 用于信息查看
    .setDestinationInExternalPublicDir(
    Environment.DIRECTORY_DOWNLOADS, "2.zip");
    mDownloadId = downloadManager.enqueue(request); // 加入下載隊(duì)列
    
    startQuery(mDownloadId);
      

4.移除(停止)下載

private int removeDownload(long downloadId) {
    return downloadManager.remove(downloadId);
}

5.監(jiān)聽下載的完成

@Override
protected void onPause() {
    stopQuery();
    this.unregisterReceiver(receiver);

    super.onPause();
}

@Override
protected void onResume() {
    IntentFilter filter = new IntentFilter(
            DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    this.registerReceiver(receiver, filter);

    IntentFilter filter22 = new IntentFilter(
            DownloadManager.ACTION_NOTIFICATION_CLICKED);
    this.registerReceiver(receiver2, filter22);

    startQuery(mDownloadId);
    super.onResume();
}

// 監(jiān)聽下載結(jié)束,啟用BroadcastReceiver
BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

            long downloadId = intent.getLongExtra(
                    DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            // 查詢
            Query query = new Query();
            query.setFilterById(downloadId);
            Cursor c = dm.query(query);
            if (c.moveToFirst()) {
                int columnIndex = c
                        .getColumnIndex(DownloadManager.COLUMN_STATUS);
                if (DownloadManager.STATUS_SUCCESSFUL == c
                        .getInt(columnIndex)) {

                    String uriString = c
                            .getString(c
                                    .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

                    //removeDownload(downloadId);
                    Toast.makeText(MainActivity.this,
                            "get file complete: " + uriString, 0).show();
                    // Uri.parse(uriString);
                }
            }// endif

        }// endif

    }// onReceive
};// end class receiver

6.在下載過程中腰耙,查看狀態(tài)

class QueryRunnable implements Runnable {
    public long DownID;

    @Override
    public void run() {
        queryState(DownID);
        handler.postDelayed(runnable, step);
    }
};

private void startQuery(long downloadId) {
    if (downloadId != 0) {
        runnable.DownID = downloadId;
        handler.postDelayed(runnable, step);
    }

};

private void stopQuery() {
    handler.removeCallbacks(runnable);
}

private void queryState(long downID) {
    // 關(guān)鍵:通過ID向下載管理查詢下載情況榛丢,返回一個(gè)cursor
    Cursor c = downloadManager.query(new DownloadManager.Query()
            .setFilterById(downID));
    if (c == null) {
        Toast.makeText(this, "Download not found!", Toast.LENGTH_LONG)
                .show();
    } else { // 以下是從游標(biāo)中進(jìn)行信息提取
        if(!c.moveToFirst()){
            c.close();
            return;
        }
        Log.d(TAG,
                "Column_id : "
                        + c.getLong(c
                                .getColumnIndex(DownloadManager.COLUMN_ID)));
        Log.d(TAG,
                "Column_bytes_downloaded so far : "
                        + c.getLong(c
                                .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)));
        Log.d(TAG,
                "Column last modified timestamp : "
                        + c.getLong(c
                                .getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP)));
        Log.d(TAG,
                "Column local uri : "
                        + c.getString(c
                                .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
        Log.d(TAG,
                "Column statue : "
                        + c.getInt(c
                                .getColumnIndex(DownloadManager.COLUMN_STATUS)));
        Log.d(TAG,
                "Column reason : "
                        + c.getInt(c
                                .getColumnIndex(DownloadManager.COLUMN_REASON)));

        int st = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
        Toast.makeText(this, statusMessage(st), Toast.LENGTH_LONG).show();
        //Log.i(TAG, statusMessage(st));
        
        c.close();
    }
}

private String statusMessage(int st) {
    switch (st) {
    case DownloadManager.STATUS_FAILED:
        return "Download failed";
    case DownloadManager.STATUS_PAUSED:
        return "Download paused";
    case DownloadManager.STATUS_PENDING:
        return "Download pending";
    case DownloadManager.STATUS_RUNNING:
        return "Download in progress!";
    case DownloadManager.STATUS_SUCCESSFUL:
        return "Download finished";
    default:
        return "Unknown Information";
    }
}

完整代碼

    package example.downloaddemo;
    
    import java.io.File;
    
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.os.Handler;
    import android.os.Message;
    import android.app.Activity;
    import android.app.DownloadManager;
    import android.app.DownloadManager.Query;
    import android.app.DownloadManager.Request;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.database.Cursor;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Toast;
    
    /**
     * 參考:http://blog.csdn.net/flowingflying/article/details/6925683
     * @author yunfei
     *
     */
    public class MainActivity extends Activity {
        private static final String TAG = "PDWY";
        // an ID for the download, unique across the system. This ID is used to make
        // future calls related to this download.
        long mDownloadId;
        DownloadManager downloadManager;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            // 過SystemService 以獲取 DownloadManager
            downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    
        }
    
        @Override
        protected void onPause() {
            stopQuery();
            this.unregisterReceiver(receiver);
    
            super.onPause();
        }
    
        @Override
        protected void onResume() {
            IntentFilter filter = new IntentFilter(
                    DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            this.registerReceiver(receiver, filter);
    
            IntentFilter filter22 = new IntentFilter(
                    DownloadManager.ACTION_NOTIFICATION_CLICKED);
            this.registerReceiver(receiver2, filter22);
    
            startQuery(mDownloadId);
            super.onResume();
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }
    
        public void lookDownload() {
            startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
        }
    
        public void onClick(View view) {
            int id = view.getId();
            if (id == R.id.start) {
                Request request = new Request(
                        Uri.parse("http://192.168.3.123:8080/androidautoupdate/apks/2.zip"));
    
                request.setAllowedNetworkTypes(
                        DownloadManager.Request.NETWORK_MOBILE
                                | DownloadManager.Request.NETWORK_WIFI)
                        .setAllowedOverRoaming(false) // 缺省是true
                        .setTitle("更新") // 用于信息查看
                        .setDescription("下載apk") // 用于信息查看
                        .setDestinationInExternalPublicDir(
                                Environment.DIRECTORY_DOWNLOADS, "2.zip");
                mDownloadId = downloadManager.enqueue(request); // 加入下載隊(duì)列
    
                startQuery(mDownloadId);
            }
            if (id == R.id.stop) {
                stopQuery();
                removeDownload(mDownloadId);
            }
            if (id == R.id.look) {
                lookDownload();
            }
        }
    
        private int removeDownload(long downloadId) {
            return downloadManager.remove(downloadId);
        }
    
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
            }
    
        };
    
        int step = 1000;
        QueryRunnable runnable = new QueryRunnable();
    
        class QueryRunnable implements Runnable {
            public long DownID;
    
            @Override
            public void run() {
                queryState(DownID);
                handler.postDelayed(runnable, step);
            }
        };
    
        private void startQuery(long downloadId) {
            if (downloadId != 0) {
                runnable.DownID = downloadId;
                handler.postDelayed(runnable, step);
            }
    
        };
    
        private void stopQuery() {
            handler.removeCallbacks(runnable);
        }
    
        private void queryState(long downID) {
            // 關(guān)鍵:通過ID向下載管理查詢下載情況,返回一個(gè)cursor
            Cursor c = downloadManager.query(new DownloadManager.Query()
                    .setFilterById(downID));
            if (c == null) {
                Toast.makeText(this, "Download not found!", Toast.LENGTH_LONG)
                        .show();
            } else { // 以下是從游標(biāo)中進(jìn)行信息提取
                if(!c.moveToFirst()){
                    c.close();
                    return;
                }
                Log.d(TAG,
                        "Column_id : "
                                + c.getLong(c
                                        .getColumnIndex(DownloadManager.COLUMN_ID)));
                Log.d(TAG,
                        "Column_bytes_downloaded so far : "
                                + c.getLong(c
                                        .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)));
                Log.d(TAG,
                        "Column last modified timestamp : "
                                + c.getLong(c
                                        .getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP)));
                Log.d(TAG,
                        "Column local uri : "
                                + c.getString(c
                                        .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
                Log.d(TAG,
                        "Column statue : "
                                + c.getInt(c
                                        .getColumnIndex(DownloadManager.COLUMN_STATUS)));
                Log.d(TAG,
                        "Column reason : "
                                + c.getInt(c
                                        .getColumnIndex(DownloadManager.COLUMN_REASON)));
    
                int st = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                Toast.makeText(this, statusMessage(st), Toast.LENGTH_LONG).show();
                //Log.i(TAG, statusMessage(st));
                
                c.close();
            }
        }
    
        private String statusMessage(int st) {
            switch (st) {
            case DownloadManager.STATUS_FAILED:
                return "Download failed";
            case DownloadManager.STATUS_PAUSED:
                return "Download paused";
            case DownloadManager.STATUS_PENDING:
                return "Download pending";
            case DownloadManager.STATUS_RUNNING:
                return "Download in progress!";
            case DownloadManager.STATUS_SUCCESSFUL:
                return "Download finished";
            default:
                return "Unknown Information";
            }
        }
    
        // 監(jiān)聽下載結(jié)束挺庞,啟用BroadcastReceiver
        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
    
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                String action = intent.getAction();
                if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
    
                    long downloadId = intent.getLongExtra(
                            DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                    // 查詢
                    Query query = new Query();
                    query.setFilterById(downloadId);
                    Cursor c = dm.query(query);
                    if (c.moveToFirst()) {
                        int columnIndex = c
                                .getColumnIndex(DownloadManager.COLUMN_STATUS);
                        if (DownloadManager.STATUS_SUCCESSFUL == c
                                .getInt(columnIndex)) {
    
                            String uriString = c
                                    .getString(c
                                            .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
    
                            //removeDownload(downloadId);
                            Toast.makeText(MainActivity.this,
                                    "get file complete: " + uriString, 0).show();
                            // Uri.parse(uriString);
                        }
                    }// endif
    
                }// endif
    
            }// onReceive
        };// end class receiver
    
        // 監(jiān)聽下載結(jié)束晰赞,啟用BroadcastReceiver
        BroadcastReceiver receiver2 = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                long downloadId = intent.getLongExtra(
                        DownloadManager.EXTRA_DOWNLOAD_ID, 0);
    
                String action = intent.getAction();
                if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
                    lookDownload();
                }
            }
        };//
    }
      

參考資料

http://developer.android.com/intl/zh-CN/reference/android/app/DownloadManager.html

http://blog.csdn.net/gf771115/article/details/7019033

http://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市选侨,隨后出現(xiàn)的幾起案子掖鱼,更是在濱河造成了極大的恐慌,老刑警劉巖援制,帶你破解...
    沈念sama閱讀 211,884評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件戏挡,死亡現(xiàn)場離奇詭異,居然都是意外死亡晨仑,警方通過查閱死者的電腦和手機(jī)褐墅,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,347評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來洪己,“玉大人妥凳,你說我怎么就攤上這事〈鸩叮” “怎么了逝钥?”我有些...
    開封第一講書人閱讀 157,435評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長噪珊。 經(jīng)常有香客問我晌缘,道長,這世上最難降的妖魔是什么痢站? 我笑而不...
    開封第一講書人閱讀 56,509評(píng)論 1 284
  • 正文 為了忘掉前任磷箕,我火速辦了婚禮,結(jié)果婚禮上阵难,老公的妹妹穿的比我還像新娘岳枷。我一直安慰自己,他們只是感情好呜叫,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,611評(píng)論 6 386
  • 文/花漫 我一把揭開白布空繁。 她就那樣靜靜地躺著,像睡著了一般朱庆。 火紅的嫁衣襯著肌膚如雪盛泡。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,837評(píng)論 1 290
  • 那天娱颊,我揣著相機(jī)與錄音傲诵,去河邊找鬼凯砍。 笑死,一個(gè)胖子當(dāng)著我的面吹牛拴竹,可吹牛的內(nèi)容都是我干的悟衩。 我是一名探鬼主播,決...
    沈念sama閱讀 38,987評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼栓拜,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼座泳!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起幕与,我...
    開封第一講書人閱讀 37,730評(píng)論 0 267
  • 序言:老撾萬榮一對(duì)情侶失蹤挑势,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后啦鸣,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體薛耻,經(jīng)...
    沈念sama閱讀 44,194評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,525評(píng)論 2 327
  • 正文 我和宋清朗相戀三年赏陵,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片饲漾。...
    茶點(diǎn)故事閱讀 38,664評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蝙搔,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出考传,到底是詐尸還是另有隱情吃型,我是刑警寧澤,帶...
    沈念sama閱讀 34,334評(píng)論 4 330
  • 正文 年R本政府宣布僚楞,位于F島的核電站勤晚,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏泉褐。R本人自食惡果不足惜赐写,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,944評(píng)論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望膜赃。 院中可真熱鬧挺邀,春花似錦、人聲如沸跳座。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,764評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽疲眷。三九已至禾蚕,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間狂丝,已是汗流浹背换淆。 一陣腳步聲響...
    開封第一講書人閱讀 31,997評(píng)論 1 266
  • 我被黑心中介騙來泰國打工哗总, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人产舞。 一個(gè)月前我還...
    沈念sama閱讀 46,389評(píng)論 2 360
  • 正文 我出身青樓魂奥,卻偏偏與公主長得像,于是被迫代替她去往敵國和親易猫。 傳聞我的和親對(duì)象是個(gè)殘疾皇子耻煤,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,554評(píng)論 2 349

推薦閱讀更多精彩內(nèi)容

  • afinalAfinal是一個(gè)android的ioc,orm框架 https://github.com/yangf...
    passiontim閱讀 15,411評(píng)論 2 45
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 171,791評(píng)論 25 707
  • 那年初二准颓,你我初同桌哈蝇,你說,我分手了攘已,看炮赦,這是我的分手信,我笑著說好惡心样勃。 某次上課吠勘,你一直盯著我看,我看了你一眼...
    葉子爹爹閱讀 342評(píng)論 0 0
  • 親愛的一安:最近媽媽受情書群媽媽們的影響峡眶,下了個(gè)得到APP剧防,每天聽一本書,完成每天的學(xué)習(xí)任務(wù)辫樱,今天我看到了一篇寫如...
    Rita許閱讀 177評(píng)論 0 0
  • 貝蒂娜追求生活的不朽,一生追逐于歌德生活搬男。以年齡為隱藏拣展,倚小裝小,親近歌德止后,做他永遠(yuǎn)的贊賞者瞎惫。又毫不客氣的...
    半道殘陽鋪水中閱讀 500評(píng)論 0 3