使用Android自带DownloadManager下载文件

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

直接看实例代码:
package com.hebaijun.downloadtest;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.webkit.MimeTypeMap;

public class DownloadTestActivity extends Activity {
	private DownloadManager downloadManager;
	private SharedPreferences prefs;
	private static final String DL_ID = "downloadId";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
        prefs = PreferenceManager.getDefaultSharedPreferences(this); 
    }
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unregisterReceiver(receiver);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(!prefs.contains(DL_ID)) { 
			String url = "http://10.0.2.2/android/film/G3.mp4";
	        //开始下载 
	        Uri resource = Uri.parse(encodeGB(url)); 
	        DownloadManager.Request request = new DownloadManager.Request(resource); 
	        request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI); 
	        request.setAllowedOverRoaming(false); 
	        //设置文件类型
	        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
	        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
	        request.setMimeType(mimeString);
	        //在通知栏中显示 
	        request.setShowRunningNotification(true);
	        request.setVisibleInDownloadsUi(true);
	        //sdcard的目录下的download文件夹
	        request.setDestinationInExternalPublicDir("/download/", "G3.mp4");
	        request.setTitle("移动G3广告"); 
	        long id = downloadManager.enqueue(request); 
	        //保存id 
	        prefs.edit().putLong(DL_ID, id).commit(); 
	    } else { 
	        //下载已经开始,检查状态
	        queryDownloadStatus(); 
	    } 

	    registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
	}
	
	/**
	 * 如果服务器不支持中文路径的情况下需要转换url的编码。
	 * @param string
	 * @return
	 */
	public String encodeGB(String string)
	{
		//转换中文编码
		String split[] = string.split("/");
		for (int i = 1; i < split.length; i++) {
			try {
				split[i] = URLEncoder.encode(split[i], "GB2312");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			split[0] = split[0]+"/"+split[i];
		}
		split[0] = split[0].replaceAll("\\+", "%20");//处理空格
		return split[0];
	}
	
	private BroadcastReceiver receiver = new BroadcastReceiver() { 
	    @Override 
	    public void onReceive(Context context, Intent intent) { 
	    	//这里可以取得下载的id,这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听
	    	Log.v("intent", ""+intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));
	        queryDownloadStatus(); 
	    } 
	}; 
	
	private void queryDownloadStatus() { 
	    DownloadManager.Query query = new DownloadManager.Query(); 
	    query.setFilterById(prefs.getLong(DL_ID, 0)); 
	    Cursor c = downloadManager.query(query); 
	    if(c.moveToFirst()) { 
	        int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)); 
	        switch(status) { 
	        case DownloadManager.STATUS_PAUSED: 
	        	Log.v("down", "STATUS_PAUSED");
	        case DownloadManager.STATUS_PENDING: 
	        	Log.v("down", "STATUS_PENDING");
	        case DownloadManager.STATUS_RUNNING: 
	            //正在下载,不做任何事情
	        	Log.v("down", "STATUS_RUNNING");
	            break; 
	        case DownloadManager.STATUS_SUCCESSFUL: 
	            //完成
	            Log.v("down", "下载完成");
	            break; 
	        case DownloadManager.STATUS_FAILED: 
	            //清除已下载的内容,重新下载
	        	Log.v("down", "STATUS_FAILED");
	        	downloadManager.remove(prefs.getLong(DL_ID, 0)); 
	            prefs.edit().clear().commit(); 
	            break; 
	        } 
	    }
	}
}

最后需要的权限是:
<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"/>
  • 1
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值