Android studio 使用原生自带DownloadManager实现app下载更新

安卓中的DownLoadManag是安卓自带的下载类专门用来下载文件,自API9开始就用这个类可以说兼容性是没问题的了,在开发中如果android给我们提供了该工具我们就没必要去重新写,避免了错误和兼容性的发生,下面我就以App下载更新的列子简单的讲下它的使用

直接看代码:代码完整直接复制来用

public class AppUpdataManger {
    private DownloadManager downloadManager;
    private Context mContext;
    private long mTaskId;
    private String downloadPath;
    private String versionName;
    private String tag="下载管理类";
    public AppUpdataManger(Context context){
        this.mContext=context;

    }
    //广播接收者,接收下载状态
    private BroadcastReceiver receiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkDownloadStatus();//检查下载状态
        }
    };
    //使用系统下载器下载
    public void downloadAPK(String versionUrl, String versionName) {
        this.versionName=versionName;
        Log.e("下载",versionUrl+versionName);
        //将下载请求加入下载队列
        downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        //创建下载任务
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(versionUrl));
        request.setAllowedOverRoaming(false);//漫游网络是否可以下载
        //设置文件类型,可以在下载结束后自动打开该文件
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(versionUrl));
        request.setMimeType(mimeString);//加入任务队列
        //在通知栏显示,默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setAllowedOverRoaming(false);
        request.setVisibleInDownloadsUi(true);
        //sdcard的目录下的download文件夹,必须设置
//        request.setDestinationInExternalPublicDir("/sdcard/download", versionName);
        //自定义路径的方法
        request.setDestinationInExternalFilesDir(mContext,Environment.DIRECTORY_DOWNLOADS,versionName);

        //加入下载列后会给该任务返回一个long型的id,
        //通过该id可以取消任务,重启任务等等
        mTaskId=downloadManager.enqueue(request);
        //注册广播接收,监听下载状态
        mContext.registerReceiver(receiver,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

    }


    //检查下载状态
    private void checkDownloadStatus(){
        DownloadManager.Query query=new DownloadManager.Query();
        query.setFilterById(mTaskId);//赛选下载任务,传入任务ID,可变参数
        Cursor cursor=downloadManager.query(query);
        if (cursor.moveToFirst()){
            int status=cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status){
                case DownloadManager.STATUS_PAUSED:
                    //下载暂停
                    Log.d(tag,"下载暂停");
                    break;
                case DownloadManager.STATUS_PENDING:
                    //下载延迟
                    Log.d(tag,"下载延迟");
                    break;
                case DownloadManager.STATUS_RUNNING:
                    //正在下载
                    Log.d(tag,"正在下载");
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    Toast.makeText(mContext,"下载完成",Toast.LENGTH_LONG).show();
                    //打开文件进行安装
                    installAPK(mTaskId);
                    break;
                case DownloadManager.STATUS_FAILED:
                    //下载失败
                    Log.d(tag,"下载失败");
                    Toast.makeText(mContext,"更新失败",Toast.LENGTH_LONG).show();
                    break;

            }
        }
        cursor.close();
    }

    //下载到本地后执行安装根据获得的id进行安装
    protected void installAPK(long appId){
        Intent install = new Intent(Intent.ACTION_VIEW);
        Uri downloadFileUri = downloadManager
                .getUriForDownloadedFile(appId);
        install.setDataAndType(downloadFileUri,
                "application/vnd.android.package-archive");
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(install);



    }
}

在Activity中调用

appUpdataManger=new AppUpdataManger(this);
appUpdataManger.downloadAPK(mUrl,"我的应用");

所需要的权限
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
android:name="android.permission.READ_EXTERNAL_STORAGE"/>

android:name="android.permission.INTERNET"/>


个人建议在server中调用免得用户离开这个页面造成停止下载,直接把最上面的那段代码复制到server中
startService()
时调用
下面我也把demo地址贴出来出什么问题了自己去看看

demo:地址   http://download.csdn.net/detail/liufatao/9739677








你可能感兴趣的:(Android,功能类)