Android系统自带下载器DownloadManager

/**
 * 系统下载器下载
 *
 * @author Administrator
 * @date 2019/4/1
 */

public class SystemDownManagerUtils {

    private static DownloadManager downloadManager;
    private static SystemDownLoadCompleteReceiver receiver;

    public static void init(Context context, boolean isRegisterReceiver) {
        //获取系统服务
        downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        if (isRegisterReceiver) {
            registerReceiver(context);
        }
    }

    public static void registerReceiver(Context context) {
        receiver = new SystemDownLoadCompleteReceiver();
        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        context.registerReceiver(receiver, filter);
    }

    public static void downLoadFile(Context context, String url, String descriptionMessage) {
        //创建request对象
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        //设置什么网络情况下可以下载
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        /**
         * Request.VISIBILITY_VISIBLE
         *在下载进行的过程中,通知栏中会一直显示该下载的Notification,当下载完成时,该Notification会被移除,这是默认的参数值。
         *
         * Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
         *在下载过程中通知栏会一直显示该下载的Notification,在下载完成后该Notification会继续显示,直到用户点击该Notification或者消除该Notification。
         *
         * Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION
         *只有在下载完成后该Notification才会被显示。
         *
         * Request.VISIBILITY_HIDDEN
         *不显示该下载请求的Notification。如果要使用这个参数,需要在应用的清单文件中加上DOWNLOAD_WITHOUT_NOTIFICATION权限。
         *
         *
         */
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        //设置通知栏的标题
        request.setTitle("下载");
        //设置通知栏的message
        request.setDescription(descriptionMessage);
        //设置漫游状态下是否可以下载
        request.setAllowedOverRoaming(false);
        //设置文件存放目录
        request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, getFileName(url));
        //进行下载
        downloadManager.enqueue(request);
    }

    public static void downLoadFile(Context context, String url) {
        //创建request对象
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        //设置什么网络情况下可以下载
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        /**
         * Request.VISIBILITY_VISIBLE
         *在下载进行的过程中,通知栏中会一直显示该下载的Notification,当下载完成时,该Notification会被移除,这是默认的参数值。
         *
         * Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
         *在下载过程中通知栏会一直显示该下载的Notification,在下载完成后该Notification会继续显示,直到用户点击该Notification或者消除该Notification。
         *
         * Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION
         *只有在下载完成后该Notification才会被显示。
         *
         * Request.VISIBILITY_HIDDEN
         *不显示该下载请求的Notification。如果要使用这个参数,需要在应用的清单文件中加上DOWNLOAD_WITHOUT_NOTIFICATION权限。
         *
         *
         */
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        //设置通知栏的标题
        request.setTitle("下载");
        //设置通知栏的message
        request.setDescription("正在下载");
        //设置漫游状态下是否可以下载
        request.setAllowedOverRoaming(false);
        //设置文件存放目录
        request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, getFileName(url));
        //进行下载
        downloadManager.enqueue(request);
    }

    public static String getFileName(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }
}

广播:以下广播是执行下载apk完成后自动安装的广播,如需执行其他文件下载操作,自行修改

/**
 * 系统下载管理器广播
 *
 * @author freak
 */
public class SystemDownLoadCompleteReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
            //在广播中取出下载任务的id
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            LogUtil.e("编号:" + id + "的下载任务已经完成!");
            Toast.makeText(context, "编号:" + id + "的下载任务已经完成!", Toast.LENGTH_SHORT).show();
            DownloadManager.Query query = new DownloadManager.Query();
            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            query.setFilterById(id);
            Cursor c = dm.query(query);
            if (c != null) {
                try {
                    if (c.moveToFirst()) {
                        //获取文件下载路径
                        String filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                        int status = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
                        if (status == DownloadManager.STATUS_SUCCESSFUL) {
                            //启动更新
                            Uri uri = Uri.fromFile(new File(filename));
                            if (uri != null) {
                                Intent install = new Intent(Intent.ACTION_VIEW);
                                install.setDataAndType(uri, "application/vnd.android.package-archive");
                                install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(install);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                } finally {
                    c.close();
                }

            }
        }
    }

}

配置权限:

<!--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" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

注册广播:

<receiver android:name=".receiver.SystemDownLoadCompleteReceiver">
    <intent-filter>
        <action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
    </intent-filter>
</receiver>

猜你喜欢

转载自blog.csdn.net/freak_csh/article/details/88962452