android开发DownloadManager文件下载的操作实例

今天写了一个文件下载的实用类,实现了文件下载、打开安装或者显示。。。。

APP界面图:

QQ截图20160529155520

 

下载中的效果图:

QQ截图20160529155506

MainActivity中的按钮事件代码:

downmanager = (Button)findViewById(R.id.downManager);

downmanager.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        downManagerEx.doDown("http://sqdd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk"
        ,"QQ V6.3.7","QQ轻聊版",downManagerEx.NETWORK_MOBILE|downManagerEx.NETWORK_WIFI,false);

    }
});

申请的权限有2个:

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

主要是上网权限跟写入内存卡的权限。

DownManagerEx 类的源代码:
package com.lanxin.servicetest;

import android.app.DownloadManager;
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.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

import java.io.File;


/**
 * Created by Alan on 2016/5/29 0029.
 */
public class DownManagerEx {

    private static final String TAG = "DownManagerEx";
    private static final String DownLoadId = "DownLoadId";
    private DownloadManager dmgr = null;
    private DownloadManager.Request dmgreqs = null;
    private IntentFilter intentFilter;
    private Context mContext;
    private SharedPreferences sp;

    private long downLoadId = -1;

    //下载完毕后是否自动安装程序
    private boolean isAutoOpen = false;

    public int NETWORK_MOBILE = DownloadManager.Request.NETWORK_MOBILE;
    public int NETWORK_WIFI = DownloadManager.Request.NETWORK_WIFI;
    
    //初始化的时候传入了一个上下文
    public DownManagerEx(Context ctx){
        mContext = ctx;

    }

    /**
     * 文件下载任务
     * @param url 下载文件的地址
     * @param tilte bar提示标题
     * @param des bar提示备注
     * @param netWorkType 网络类型:DownloadManager.Request.NETWORK_MOBILE OR DownloadManager.Request.NETWORK_WIFI
     * @return
     */
    public Long doDown(String url,String tilte,String des,int netWorkType,boolean isopen){

        isAutoOpen = isopen;//传入是否自动安装、打开文件

        if(!sp.contains(DownLoadId)){//为了避免重复下载,这里加了个判断,用来判断文件是否已经在下载中
            String endname = url.substring(url.lastIndexOf("/")).toLowerCase();//获取文件的后缀名,然后通过后缀名返回文件类型信息

            dmgreqs = new DownloadManager.Request(Uri.parse(url));

            dmgreqs.setTitle(tilte);
            dmgreqs.setDescription(des);
            dmgreqs.setAllowedNetworkTypes(netWorkType);
            dmgreqs.setAllowedOverRoaming(false);
            dmgreqs.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            dmgreqs.setMimeType(getEndsWithType(endname));//设置文件头类型

            dmgreqs.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, endname);//设置下载的目录,这里是下载到内存卡的dowload目录下
            dmgreqs.allowScanningByMediaScanner();
            dmgreqs.setVisibleInDownloadsUi(true);//设置为可见可管理


            intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

            mContext.registerReceiver(receiver,intentFilter);

            downLoadId = dmgr.enqueue(dmgreqs);

            sp.edit().putLong(DownLoadId,downLoadId).commit(); //保存当前下载的ID
            Log.i(TAG,""+downLoadId);
        }else{
            QueryDownStatus();
        }


        return downLoadId;

    }

    /**
     * 广播接收器
     */
    public BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();

            long doId = bundle.getLong(DownloadManager.EXTRA_DOWNLOAD_ID);

            Log.i(TAG,"下载完毕");

            if(downLoadId == doId){

                try {

                    //获取URI
                    Uri uri = dmgr.getUriForDownloadedFile(downLoadId);

                    Log.i(TAG, uri.getEncodedPath());

                    //打开文件
                    openFile(new File(uri.getEncodedPath()));
                    sp.edit().clear().commit();//下载完成后,我们要清除任务ID
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /**
     * Activity在onResume激活此事件
     */
    public void downResume(){
        dmgr = (DownloadManager)mContext.getSystemService(mContext.DOWNLOAD_SERVICE);
        sp = PreferenceManager.getDefaultSharedPreferences(mContext);
    }

    /**
     * Activity在onPause的时候激活此事件
     */
    public void downPause(){
        if(dmgreqs != null){
            mContext.unregisterReceiver(receiver);
            dmgr = null;
        }

    }

    /**
     * 为了避免重复下载,做了个状态查询
     */
    public void QueryDownStatus(){
        DownloadManager.Query dmQ = new DownloadManager.Query();
        long _id = sp.getLong(DownLoadId, 0);

        dmQ.setFilterById(_id);
        Cursor c = dmgr.query(dmQ);
        if(c.moveToNext()){
            int s = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));

            switch (s){
                case DownloadManager.STATUS_PAUSED:
                case DownloadManager.STATUS_RUNNING:
                case DownloadManager.STATUS_PENDING:
                    Log.i(TAG,"下载中...");
                    Toast.makeText(mContext,"文件下载中...",Toast.LENGTH_LONG).show();
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    //下载完成

                    Uri uri = dmgr.getUriForDownloadedFile(_id);

                    Log.i(TAG,uri.getEncodedPath());

                    isAutoOpen = true;

                    openFile(new File(uri.getEncodedPath()));
                    sp.edit().clear().commit();
                    break;
                case DownloadManager.STATUS_FAILED:
                    //死掉
                    dmgr.remove(_id);
                    sp.edit().clear().commit();
                    break;

            }
        }
    }

    /**
     * 打开文件
     * @param file
     */
    public void openFile(File file){
        if(!isAutoOpen){
            return;
        }
        Intent intent = new Intent();

        String fileName = file.getAbsolutePath();
        if(fileName.endsWith(".png") || fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".gif")){

            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "image/*");
            mContext.startActivity(intent);

        }else if(fileName.endsWith(".mp4")
                || fileName.endsWith(".3gp")
                || fileName.endsWith(".avi")
                || fileName.endsWith(".flv")
                || fileName.endsWith(".wmv")
                || fileName.endsWith(".rmvb")
                || fileName.endsWith(".asf")
                || fileName.endsWith(".mkv")
                || fileName.endsWith(".mpg")){

            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "video/*");
            mContext.startActivity(intent);
        }else if(fileName.endsWith(".mp3")
                || fileName.endsWith(".ogg")
                || fileName.endsWith(".ape")){

            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "audio/*");
            mContext.startActivity(intent);
        }else if(fileName.endsWith(".apk")){
            intent.setAction("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        }
    }

    /**
     * 返回文件类型
     * @param filePath 文件的路径比如:http://192.168.1.107/1.mp3
     * @return
     */
    public String getEndsWithType(String filePath){
        if(filePath.endsWith(".apk")){
            return "application/vnd.android.package-archive";
        }else if(filePath.endsWith(".png") || filePath.endsWith(".jpg") || filePath.endsWith(".jpeg") || filePath.endsWith(".gif")){
            return "image/*";
        }else if(filePath.endsWith(".mp4")
                || filePath.endsWith(".3gp")
                || filePath.endsWith(".avi")
                || filePath.endsWith(".flv")
                || filePath.endsWith(".wmv")
                || filePath.endsWith(".rmvb")
                || filePath.endsWith(".asf")
                || filePath.endsWith(".mkv")
                || filePath.endsWith(".mpg")){
            return "video/*";
        }else if(filePath.endsWith(".mp3")
                || filePath.endsWith(".ogg")
                || filePath.endsWith(".ape")){
            return "audio/*";
        }

        return "";

    }
}

 

源代码下载链接:http://pan.baidu.com/s/1i54OkKX 密码:beuv

 

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |