//主要方法
public void downloadApk(String downloadUrl) {
clearApk(getString(R.string.app_name) + ".apk");
//TODO 1.封装下载请求
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
request.setMimeType("application/vnd.android.package-archive");
// //TODO 2.下载标题,描述
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setTitle(getString(R.string.app_name));
request.setDescription(getString(R.string.app_name) + "下载");
// TODO 3.设置下载文件的保存位置
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, getString(R.string.app_name) + ".apk");
// TODO 4.获取下载管理器服务的实例, 添加下载任务
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);// 将下载请求加入下载队列, 返回一个下载ID
}
//清除重复的Apk防止重复下载
public static File clearApk(String apkName) {
File apkFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), apkName);
if (apkFile.exists()) {
apkFile.delete();
}
return apkFile;
}