1、使用DownloadReceiver下载apk:
/**
* 下载apk文件
* @param path apk的下载地址url
*/
private void downApkLoad(String path) {
//app的下载地址
Uri uri = Uri.parse(path);
DownloadManager.Request req = new DownloadManager.Request(uri);
//设置网络状态下进行更新
req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE|DownloadManager.Request.NETWORK_WIFI);
//下载中和下载完后都·显示通知栏
req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//使用系统默认的下载路径 此处为应用内 /android/data/packages ,所以兼容7.0 8.0
req.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS, getResources().getString(R.string.app_name) + ".apk");
//通知栏标题
req.setTitle(getResources().getString(R.string.app_name));
//通知栏描述信息
req.setDescription("下载中");
//设置类型为.apk
req.setMimeType("application/vnd.android.package-archive");
req.setVisibleInDownloadsUi(true);
//获取下载任务ID
DownloadManager dm = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
BaseApplication.downloadId = dm.enqueue(req);
registerReceiver(new DownloadReceiver(), new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Toast.makeText(mContext,"下载中,您可以在通知栏查看进度!",Toast.LENGTH_LONG).show();
}
2、注册的DownloadReceiver:
public class DownloadReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//根据id判断如果文件已经下载成功返回保存文件的路径
Uri downloadFileUri = dManager.getUriForDownloadedFile(BaseApplication.downloadId);
Log.d("DownloadManager", "apk存储路径 : " + downloadFileUri);
install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
if (downloadFileUri != null) {
if ((Build.VERSION.SDK_INT >= 24)) {//判读版本是否在7.0以上
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//添加这一句表示对目标应用临时授权该Uri所代表的文件
// 不添加无法安装 或者出现解析包异常
}
context.startActivity(install);
}
}
}