DownloadManager 的使用


一、基本概念
    1、DownloadManager是Android 2.3A (API level 9) 引入的,基於http協議,用於處理長時間下載。

    2、DownloadManager對於斷點續傳功能支持很好 。

 

二、權限設置(由於下載會需要SD卡存儲,所以需要SD卡文件讀寫權限)

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

 

三、request.setNotificationVisibility 可以用來控制什么時候顯示Notification,甚至是隱藏該request的Notification 。

   1)Request.VISIBILITY_VISIBLE

          在下載進行的過程中,通知欄中會一直顯示該下載的Notification,當下載完成時,該Notification會被移除,這是默認的參數值。

 

   (2)Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED

          在下載過程中通知欄會一直顯示該下載的Notification,在下載完成后該Notification會繼續顯示,直到用戶點擊該Notification或者消除該Notification。

 

   (3)Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION

         只有在下載完成后該Notification才會被顯示。

 

    (4)Request.VISIBILITY_HIDDEN

          不顯示該下載請求的Notification。如果要使用這個參數,需要在應用的清單文件中加上DOWNLOAD_WITHOUT_NOTIFICATION權限。

 

 相對應的代碼

   //設置狀態欄中顯示Notification

     //設置Notification的標題

    request.setTitle( "微信下載" ) ;

    request.setDescription( "5.3.6" ) ;


    request.setNotificationVisibility( Request.VISIBILITY_VISIBLE ) ;

    request.setNotificationVisibility( Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED ) ;

    request.setNotificationVisibility( Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION ) ;

    request.setNotificationVisibility( Request.VISIBILITY_HIDDEN ) ;

 

 四:下載的文件,存放路徑

/** * 設置下載文件存儲目錄 */
    void setDownloadFilePath( Request request ){ /** * 方法1: * 目錄: Android -> data -> com.app -> files -> Download -> 微信.apk * 這個文件是你的應用所專用的,軟件卸載后,下載的文件將隨着卸載全部被刪除 */

        //request.setDestinationInExternalFilesDir( this , Environment.DIRECTORY_DOWNLOADS , "微信.apk" ); 

        /** * 方法2: * 下載的文件存放地址 SD卡 download文件夾,pp.jpg * 軟件卸載后,下載的文件會保留 */
        //在SD卡上創建一個文件夾 //request.setDestinationInExternalPublicDir( "/mydownfile/" , "weixin.apk" ) ; 


        /** * 方法3: * 如果下載的文件希望被其他的應用共享 * 特別是那些你下載下來希望被Media Scanner掃描到的文件(比如音樂文件) */
        //request.setDestinationInExternalPublicDir( Environment.DIRECTORY_MUSIC, "笨小孩.mp3" ); 

        /** * 方法4 * 文件將存放在外部存儲的確實download文件內,如果無此文件夾,創建之,如果有,下面將返回false。 * 系統有個下載文件夾,比如小米手機系統下載文件夾 SD卡--> Download文件夾 */
        //創建目錄
 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir() ; //設置文件存放路徑
        request.setDestinationInExternalPublicDir(  Environment.DIRECTORY_DOWNLOADS  , "weixin.apk" ) ; }

 

五、應用實例

package com.app; 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.net.Uri; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.view.View.OnClickListener; import android.webkit.MimeTypeMap; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { String url = "http://shouji.360tpcdn.com/150527/c90d7a6a8cded5b5da95ae1ee6382875/com.tencent.mm_561.apk" ; private long  mReference = 0 ; private DownloadManager downloadManager ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView( R.layout.activity_main ) ; //取消下載
        findViewById( R.id.cancle_bt ).setOnClickListener( this ); //查看下載狀態
        findViewById( R.id.look_bt ).setOnClickListener( this ); //注冊廣播接收器
        IntentFilter filter = new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) ; registerReceiver( receiver , filter ) ; Request request = new Request( Uri.parse( url ) ); //下載網絡需求 手機數據流量、wifi
        request.setAllowedNetworkTypes( Request.NETWORK_MOBILE | Request.NETWORK_WIFI ) ; //設置是否允許漫游網絡 建立請求 默認true
        request.setAllowedOverRoaming( true ) ; //設置通知類型
 setNotification( request ) ; //設置下載路徑
 setDownloadFilePath( request ) ; /*在默認的情況下,通過Download Manager下載的文件是不能被Media Scanner掃描到的 。 進而這些下載的文件(音樂、視頻等)就不會在Gallery 和 Music Player這樣的應用中看到。 為了讓下載的音樂文件可以被其他應用掃描到,我們需要調用Request對象的 */ request.allowScanningByMediaScanner() ; /*如果我們希望下載的文件可以被系統的Downloads應用掃描到並管理, 我們需要調用Request對象的setVisibleInDownloadsUi方法,傳遞參數true。*/ request.setVisibleInDownloadsUi( true ) ; //設置請求的Mime
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); request.setMimeType(mimeTypeMap.getMimeTypeFromExtension(url)); //開始下載
        downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE) ; mReference = downloadManager.enqueue( request ) ; /* 下載管理器中有很多下載項,怎么知道一個資源已經下載過,避免重復下載呢? 我的項目中的需求就是apk更新下載,用戶點擊更新確定按鈕,第一次是直接下載, 后面如果用戶連續點擊更新確定按鈕,就不要重復下載了。 可以看出來查詢和操作數據庫查詢一樣的 */ Query query = new Query() ; query.setFilterById( mReference ); Cursor cursor = downloadManager.query( query ) ; if ( !cursor.moveToFirst() ) {// 沒有記錄 
 } else { //有記錄
 } } /** * 設置狀態欄中顯示Notification */
    void setNotification(Request request ) { //設置Notification的標題
        request.setTitle( "微信下載" ) ; //設置描述
        request.setDescription( "5.3.6" ) ; //request.setNotificationVisibility( Request.VISIBILITY_VISIBLE ) ;
 request.setNotificationVisibility( Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED ) ; //request.setNotificationVisibility( Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION ) ; //request.setNotificationVisibility( Request.VISIBILITY_HIDDEN ) ; 
 } /** * 設置下載文件存儲目錄 */
    void setDownloadFilePath( Request request ){ /** * 方法1: * 目錄: Android -> data -> com.app -> files -> Download -> 微信.apk * 這個文件是你的應用所專用的,軟件卸載后,下載的文件將隨着卸載全部被刪除 */

        //request.setDestinationInExternalFilesDir( this , Environment.DIRECTORY_DOWNLOADS , "微信.apk" ); 

        /** * 方法2: * 下載的文件存放地址 SD卡 download文件夾,pp.jpg * 軟件卸載后,下載的文件會保留 */
        //在SD卡上創建一個文件夾 //request.setDestinationInExternalPublicDir( "/mydownfile/" , "weixin.apk" ) ; 


        /** * 方法3: * 如果下載的文件希望被其他的應用共享 * 特別是那些你下載下來希望被Media Scanner掃描到的文件(比如音樂文件) */
        //request.setDestinationInExternalPublicDir( Environment.DIRECTORY_MUSIC, "笨小孩.mp3" ); 

        /** * 方法4 * 文件將存放在外部存儲的確實download文件內,如果無此文件夾,創建之,如果有,下面將返回false。 * 系統有個下載文件夾,比如小米手機系統下載文件夾 SD卡--> Download文件夾 */
        //創建目錄
 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir() ; //設置文件存放路徑
        request.setDestinationInExternalPublicDir(  Environment.DIRECTORY_DOWNLOADS  , "weixin.apk" ) ; } /** * 廣播接受器, 下載完成監聽器 */ BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction() ; if( action.equals( DownloadManager.ACTION_DOWNLOAD_COMPLETE )){ //下載完成了 //獲取當前完成任務的ID
                long  reference = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID , -1 ); Toast.makeText( MainActivity.this , "下載完成了" , Toast.LENGTH_SHORT ).show() ; //自動安裝應用
                Util util = new Util() ; util.openFile(context ); } if( action.equals( DownloadManager.ACTION_NOTIFICATION_CLICKED )){ //廣播被點擊了
                Toast.makeText( MainActivity.this , "廣播被點擊了" , Toast.LENGTH_SHORT ).show() ; } } }; @Override public void onClick(View v) { switch ( v.getId() ) { case R.id.cancle_bt : //取消下載, 如果一個下載被取消了,所有相關聯的文件,部分下載的文件和完全下載的文件都會被刪除。
 downloadManager.remove( mReference ) ; break ; case R.id.look_bt : Query query = new Query() ; query.setFilterById( mReference ); Cursor cursor = downloadManager.query( query ) ; if( cursor == null ){ Toast.makeText( MainActivity.this , "Download not found!", Toast.LENGTH_LONG ).show(); }else{  //以下是從游標中進行信息提取 
 cursor.moveToFirst(); String msg = statusMessage( cursor ) ; Toast.makeText( MainActivity.this , msg , Toast.LENGTH_SHORT ).show() ; } break; } } /** * 查詢狀態 * @param c * @return
     */
    private String statusMessage(Cursor c){ switch(c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS ))){ 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"; } } }


六:項目下載地址

http://download.csdn.net/detail/yanzi2015/8839023

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM