使用系统下载管理类DownloadManager

import java.io.File;
import java.util.HashMap;


import android.annotation.TargetApi;
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.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

/**
 * @Description: 调用系统下载管理类(api>=9)
 * @time: 2014-4-25 下午5:16:17
 * @version: 1.0
 */
public class DownloadManagerCtrl {

    private static DownloadManagerCtrl mInstance;

    private DownloadManager dm;

    private Context mContext;

    private DownloadReceiver mReceiver;

    private HashMap<String, Long> downloadQueues = new HashMap<String, Long>();

    private DownloadManagerCtrl(Context context) {
        mContext = context;
        mReceiver = new DownloadReceiver();
        dm = (DownloadManager)context.getSystemService( Context.DOWNLOAD_SERVICE);
    }

    public static synchronized DownloadManagerCtrl getInstance(Context context) {
        if(null == mInstance) {
            mInstance = new DownloadManagerCtrl( context);
        }
        return mInstance;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void addToDownload(String url) {
        Uri uri = Uri.parse( url);
        Request request = new Request( uri);
        // 设置可下载网络类型
        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.setVisibleInDownloadsUi( true);
        request.setDescription( mContext.getResources().getString( R.string.app_download_description));
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            request.setNotificationVisibility( Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        }
        else {   
            request.setShowRunningNotification( true);
        }
        // 下载路径
        String fileName = url.substring( url.lastIndexOf( '/') + 1);
        int i = fileName.indexOf( '?');
        if(i != -1) {
            fileName = fileName.substring( 0, i);
        }
        String dirType = FileUtil.getDownlaodPath( mContext);
        request.setDestinationInExternalPublicDir( dirType, fileName);
        long downloadId = dm.enqueue( request);// 加入下载队列
        downloadQueues.put( url, downloadId);
    }

    public DownloadReceiver getReceiver() {
        return mReceiver;
    }

    public void startDownload(String url) {
        if(TextUtils.isEmpty( url)) {
            return;
        }
        Long downloadId = downloadQueues.get( url);
        if(null == downloadId) {
            addToDownload( url);
        }
        else {
            checkDownloadStatus( downloadId.longValue(), url);
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void checkDownloadStatus(long downloadId, String url) {
        Query query = new Query();
        query.setFilterById( downloadId);
        Cursor c = dm.query( query);
        if(c.moveToFirst()) {
            int columnIndex = c.getColumnIndex( DownloadManager.COLUMN_STATUS);
            int status = c.getInt( columnIndex);
            System.out.println( " status " + status);
            switch(status) {
                case DownloadManager.STATUS_SUCCESSFUL:
                    // 已下载完成,若再次点击就进入安装界面
                    boolean installOk = false;
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                        installOk = startInstall( dm.getUriForDownloadedFile( downloadId));
                    }
                    else {
                        String downloadFileUrl = c.getString( c.getColumnIndex( DownloadManager.COLUMN_LOCAL_URI));
                        installOk = startInstall( Uri.parse( downloadFileUrl));
                    }
                    if(!installOk) {
                        addToDownload( url);
                    }
                    break;
                case DownloadManager.STATUS_PAUSED:
                case DownloadManager.STATUS_PENDING:
                case DownloadManager.STATUS_RUNNING:
                    // 暂定、挂起、下载中;提示已加入下载队列
                    Toast.makeText( mContext, "已加入下载队列", Toast.LENGTH_LONG).show();
                    break;
                case DownloadManager.STATUS_FAILED:
                    // 下载失败,重新下载
                    addToDownload( url);
                    break;
                default:
                    break;
            }
        }
        else {
            // 本地文件已被删除,重新下载
            addToDownload( url);
        }
        if(null != c) {
            c.close();
        }
    }

    private class DownloadReceiver extends BroadcastReceiver {

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        public void onReceive(Context context, Intent intent) {
            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)) {
                        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                            startInstall( dm.getUriForDownloadedFile( downloadId));
                        }
                        else {
                            String downloadFileUrl = c.getString( c.getColumnIndex( DownloadManager.COLUMN_LOCAL_URI));
                            startInstall( Uri.parse( downloadFileUrl));
                        }
                        c.close();
                    }
                }
            }
        }
    }

    private boolean startInstall(Uri uri) {
        if(!new File( uri.getPath()).exists()) {
            System.out.println( " local file has been deleted! ");
            return false;
        }
        Intent intent = new Intent();
        intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction( Intent.ACTION_VIEW);
        intent.setDataAndType( uri, "application/vnd.android.package-archive");
        mContext.startActivity( intent);
        return true;
    }
}

你可能感兴趣的:(使用系统下载管理类DownloadManager)