android收藏系列--Sorry的Android收藏Android开发

DownloadManager实现版本更新,监听下载进度

2016-10-24  本文已影响9352人  AJoyce_
效果图:
DownloadManager.gif

一:执行下载

downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadObserver = new DownloadChangeObserver();
//在执行下载前注册内容监听者
registerContentObserver();
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
/**设置用于下载时的网络状态*/
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
/**设置通知栏是否可见*/
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
/**设置漫游状态下是否可以下载*/
request.setAllowedOverRoaming(false);
/**如果我们希望下载的文件可以被系统的Downloads应用扫描到并管理,
 我们需要调用Request对象的setVisibleInDownloadsUi方法,传递参数true.*/
request.setVisibleInDownloadsUi(true);
/**设置文件保存路径*/
request.setDestinationInExternalFilesDir(getApplicationContext(), "phoenix", "phoenix.apk");
/**将下载请求放入队列, return下载任务的ID*/
downloadId = downloadManager.enqueue(request);
//执行下载任务时注册广播监听下载成功状态
registerBroadcast();
<!--网络通信权限-->
<uses-permission android:name="android.permission.INTERNET"/>
<!--SD卡写入数据权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--SD卡创建与删除权限-->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!--VISIBILITY_HIDDEN表示不显示任何通知栏提示的权限-->
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>
<!--DownloadManager-->
<uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
<!--版本更新服务-->
<service android:name="com.github.phoenix.service.DownloadService"></service>

二:监听下载进度

/**
 * 注册ContentObserver
 */
private void registerContentObserver() {
    /** observer download change **/
    if (downloadObserver != null) {
        getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true, downloadObserver);
    }
}
/**
 * 监听下载进度
 */
private class DownloadChangeObserver extends ContentObserver {

    public DownloadChangeObserver() {
        super(downLoadHandler);
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    }

    /**
     * 当所监听的Uri发生改变时,就会回调此方法
     *
     * @param selfChange 此值意义不大, 一般情况下该回调值false
     */
    @Override
    public void onChange(boolean selfChange) {
        scheduledExecutorService.scheduleAtFixedRate(progressRunnable, 0, 2, TimeUnit.SECONDS);
    }
}
/**
 * 通过query查询下载状态,包括已下载数据大小,总大小,下载状态
 *
 * @param downloadId
 * @return
 */
private int[] getBytesAndStatus(long downloadId) {
    int[] bytesAndStatus = new int[]{
            -1, -1, 0
    };
    DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
    Cursor cursor = null;
    try {
        cursor = downloadManager.query(query);
        if (cursor != null && cursor.moveToFirst()) {
            //已经下载文件大小
            bytesAndStatus[0] = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
            //下载文件的总大小
            bytesAndStatus[1] = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
            //下载状态
            bytesAndStatus[2] = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return bytesAndStatus;
}
private ServiceConnection conn = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        DownloadService.DownloadBinder binder = (DownloadService.DownloadBinder) service;
        DownloadService downloadService = binder.getService();

        //接口回调,下载进度
        downloadService.setOnProgressListener(new DownloadService.OnProgressListener() {
            @Override
            public void onProgress(float fraction) {
                LogUtil.i(TAG, "下载进度:" + fraction);
                bnp.setProgress((int)(fraction * 100));

                //判断是否真的下载完成进行安装了,以及是否注册绑定过服务
                if (fraction == DownloadService.UNBIND_SERVICE && isBindService) {
                    unbindService(conn);
                    isBindService = false;
                    MToast.shortToast("下载完成!");
                }
            }
        });
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
};

三:广播监听下载成功

/**
 * 安装APK
 * @param context
 * @param apkPath 安装包的路径
 */
public static void installApk(Context context, Uri apkPath) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    //此处因为上下文是Context,所以要加此Flag,不然会报错
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setDataAndType(apkPath, "application/vnd.android.package-archive");
    context.startActivity(intent);
}

四:善后处理

/**
 * 删除上次更新存储在本地的apk
 */
private void removeOldApk() {
    //获取老APK的存储路径
    File fileName = new File(SPUtil.getString(Constant.SP_DOWNLOAD_PATH, ""));
    LogUtil.i(TAG, "老APK的存储路径 =" + SPUtil.getString(Constant.SP_DOWNLOAD_PATH, ""));

    if (fileName != null && fileName.exists() && fileName.isFile()) {
        fileName.delete();
        LogUtil.i(TAG, "存储器内存在老APK,进行删除操作");
    }
}

五:具体应用
首先上传当前应用版本号给服务器,让服务器检查是否可以进行版本更新;如果可以进行版本更新,则绑定Service,开始下载APK,下载完成直接弹出安装界面,同时记录APK存储路径;待下次启动时,检查删除APK。

源码:https://github.com/GitPhoenix/DownloadManager
说明:此源码中包含了把Toast写成单列,自定义样式的代码

上一篇 下一篇

猜你喜欢

热点阅读