使用Android自带DownloadManager下载文件

SDK在API Level 9中加入了DownloadManager服务,可以将长时间的下载任务交给系统,完全由系统管理。

直接看实例代码:
[java]  view plain copy
  1. package com.hebaijun.downloadtest;  
  2.   
  3. import java.io.UnsupportedEncodingException;  
  4. import java.net.URLEncoder;  
  5.   
  6. import android.app.Activity;  
  7. import android.app.DownloadManager;  
  8. import android.app.DownloadManager.Request;  
  9. import android.content.BroadcastReceiver;  
  10. import android.content.Context;  
  11. import android.content.Intent;  
  12. import android.content.IntentFilter;  
  13. import android.content.SharedPreferences;  
  14. import android.database.Cursor;  
  15. import android.net.Uri;  
  16. import android.os.Bundle;  
  17. import android.preference.PreferenceManager;  
  18. import android.util.Log;  
  19. import android.webkit.MimeTypeMap;  
  20.   
  21. public class DownloadTestActivity extends Activity {  
  22.     private DownloadManager downloadManager;  
  23.     private SharedPreferences prefs;  
  24.     private static final String DL_ID = "downloadId";  
  25.     /** Called when the activity is first created. */  
  26.     @Override  
  27.     public void onCreate(Bundle savedInstanceState) {  
  28.         super.onCreate(savedInstanceState);  
  29.         setContentView(R.layout.main);  
  30.         downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);  
  31.         prefs = PreferenceManager.getDefaultSharedPreferences(this);   
  32.     }  
  33.     @Override  
  34.     protected void onPause() {  
  35.         // TODO Auto-generated method stub  
  36.         super.onPause();  
  37.         unregisterReceiver(receiver);  
  38.     }  
  39.     @Override  
  40.     protected void onResume() {  
  41.         // TODO Auto-generated method stub  
  42.         super.onResume();  
  43.         if(!prefs.contains(DL_ID)) {   
  44.             String url = "http://10.0.2.2/android/film/G3.mp4";  
  45.             //开始下载   
  46.             Uri resource = Uri.parse(encodeGB(url));   
  47.             DownloadManager.Request request = new DownloadManager.Request(resource);   
  48.             request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);   
  49.             request.setAllowedOverRoaming(false);   
  50.             //设置文件类型  
  51.             MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();  
  52.             String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));  
  53.             request.setMimeType(mimeString);  
  54.             //在通知栏中显示   
  55.             request.setShowRunningNotification(true);  
  56.             request.setVisibleInDownloadsUi(true);  
  57.             //sdcard的目录下的download文件夹  
  58.             request.setDestinationInExternalPublicDir("/download/""G3.mp4");  
  59.             request.setTitle("移动G3广告");   
  60.             long id = downloadManager.enqueue(request);   
  61.             //保存id   
  62.             prefs.edit().putLong(DL_ID, id).commit();   
  63.         } else {   
  64.             //下载已经开始,检查状态  
  65.             queryDownloadStatus();   
  66.         }   
  67.   
  68.         registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));  
  69.     }  
  70.       
  71.     /** 
  72.      * 如果服务器不支持中文路径的情况下需要转换url的编码。 
  73.      * @param string 
  74.      * @return 
  75.      */  
  76.     public String encodeGB(String string)  
  77.     {  
  78.         //转换中文编码  
  79.         String split[] = string.split("/");  
  80.         for (int i = 1; i < split.length; i++) {  
  81.             try {  
  82.                 split[i] = URLEncoder.encode(split[i], "GB2312");  
  83.             } catch (UnsupportedEncodingException e) {  
  84.                 e.printStackTrace();  
  85.             }  
  86.             split[0] = split[0]+"/"+split[i];  
  87.         }  
  88.         split[0] = split[0].replaceAll("\\+""%20");//处理空格  
  89.         return split[0];  
  90.     }  
  91.       
  92.     private BroadcastReceiver receiver = new BroadcastReceiver() {   
  93.         @Override   
  94.         public void onReceive(Context context, Intent intent) {   
  95.             //这里可以取得下载的id,这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听  
  96.             Log.v("intent"""+intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));  
  97.             queryDownloadStatus();   
  98.         }   
  99.     };   
  100.       
  101.     private void queryDownloadStatus() {   
  102.         DownloadManager.Query query = new DownloadManager.Query();   
  103.         query.setFilterById(prefs.getLong(DL_ID, 0));   
  104.         Cursor c = downloadManager.query(query);   
  105.         if(c.moveToFirst()) {   
  106.             int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));   
  107.             switch(status) {   
  108.             case DownloadManager.STATUS_PAUSED:   
  109.                 Log.v("down""STATUS_PAUSED");  
  110.             case DownloadManager.STATUS_PENDING:   
  111.                 Log.v("down""STATUS_PENDING");  
  112.             case DownloadManager.STATUS_RUNNING:   
  113.                 //正在下载,不做任何事情  
  114.                 Log.v("down""STATUS_RUNNING");  
  115.                 break;   
  116.             case DownloadManager.STATUS_SUCCESSFUL:   
  117.                 //完成  
  118.                 Log.v("down""下载完成");  
  119.                 break;   
  120.             case DownloadManager.STATUS_FAILED:   
  121.                 //清除已下载的内容,重新下载  
  122.                 Log.v("down""STATUS_FAILED");  
  123.                 downloadManager.remove(prefs.getLong(DL_ID, 0));   
  124.                 prefs.edit().clear().commit();   
  125.                 break;   
  126.             }   
  127.         }  
  128.     }  
  129. }  

最后需要的权限是:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
如果需要隐藏下载工具的提示和显示,修改代码:
request.setShowRunningNotification(false);
request.setVisibleInDownloadsUi(false);
加入下面的权限:
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>

http://blog.csdn.net/lixiang0522/article/details/7608310

你可能感兴趣的:(使用Android自带DownloadManager下载文件)