//首先自行判断版本号是否需要升级,这里就不做判断了
private void downFile(final String url) { new Thread(){ @Override public void run() { super.run(); DownloadUtil.get().download(url, "acct", new DownloadUtil.OnDownloadListener() { // 版本需要更新,正常下载 @Override public void onDownloadSuccess() {//下载完成 handler.sendEmptyMessage(3); } // 下载中,显示下载进度 @Override public void onDownloading(int progress) {//下载中 Message message = Message.obtain(); Bundle bundle = new Bundle(); message.what = 4; bundle.putInt("progress",progress); message.setData(bundle); handler.sendMessage(message); } @Override public void onDownloadFailed() {//下载失败 handler.sendEmptyMessage(5); } },MainActivity.this); } }.start(); }
//工具类
public class DownloadUtil { private static DownloadUtil downloadUtil; private final OkHttpClient okHttpClient; public static DownloadUtil get() { if (downloadUtil == null) { downloadUtil = new DownloadUtil(); } return downloadUtil; } public DownloadUtil() { okHttpClient = new OkHttpClient(); } /** * @param url 下载连接 * @param saveDir 储存下载文件的SDCard目录 * @param listener 下载监听 */ public void download(final String url, final String saveDir, final OnDownloadListener listener, final Activity activity) { Request request = new Request.Builder().url(url).build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 下载失败 listener.onDownloadFailed(); } @Override public void onResponse(Call call, Response response) throws IOException { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; // 储存下载文件的目录 String savePath = isExistDir(saveDir); try { is = response.body().byteStream(); long total = response.body().contentLength(); File outputImage = new File(activity.getExternalCacheDir(), getNameFromUrl(url)); try { if (outputImage.exists()){ outputImage.delete(); } outputImage.createNewFile(); } catch (IOException e) { e.printStackTrace(); } Uri imageUri; if (Build.VERSION.SDK_INT >= 24){ imageUri = FileProvider.getUriForFile(activity,"xxx.xxx.xxx.provider",outputImage); }else { imageUri = Uri.fromFile(outputImage); } // File file = new File(savePath, getNameFromUrl(url)); fos = new FileOutputStream(outputImage); long sum = 0; while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); sum += len; int progress = (int) (sum * 1.0f / total * 100); // 下载中 listener.onDownloading(progress); } fos.flush(); // 下载完成 listener.onDownloadSuccess(); } catch (Exception e) { listener.onDownloadFailed(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } } }); } /** * @param saveDir * @return * @throws IOException * 判断下载目录是否存在 */ public String isExistDir(String saveDir) throws IOException { // 下载位置 File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir); if (!downloadFile.mkdirs()) { downloadFile.createNewFile(); } String savePath = downloadFile.getAbsolutePath(); return savePath; } /** * @param url * @return * 从下载连接中解析出文件名 */ @NonNull public String getNameFromUrl(String url) { return url.substring(url.lastIndexOf("/") + 1); } public interface OnDownloadListener { /** * 下载成功 */ void onDownloadSuccess(); /** * @param progress * 下载进度 */ void onDownloading(int progress); /** * 下载失败 */ void onDownloadFailed(); } }
//记得添加
<provider android:name="android.support.v4.content.FileProvider" android:authorities="xxx.xxx.xxx.provider" //xxx为项目包名 android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" /> //xml文件下创建provider_paths </provider>
//最后别忘在res文件夹下建xml文件夹
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <!--"."表示所有路径--> <external-path name="external_files" path="."/> </paths>
private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if(msg.what==3){ Intent intent = new Intent(Intent.ACTION_VIEW); File db = null; Uri data; // 检测版本号是否大于等于24 if (Build.VERSION.SDK_INT >= 24){ db = new File(MainActivity.this.getExternalCacheDir(),url.substring(url.lastIndexOf("/") + 1)); data = FileProvider.getUriForFile(MainActivity.this, "xxx.xxx.xxx.provider", db); // 给目标应用一个临时授权 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(data, "application/vnd.android.package-archive"); }else { db = new File(MainActivity.this.getExternalCacheDir(),url.substring(url.lastIndexOf("/") + 1)); intent.setDataAndType(Uri.fromFile(db), "application/vnd.android.package-archive"); } startActivity(intent); Toast.makeText(MainActivity.this,"下载完成",Toast.LENGTH_SHORT).show(); } if(msg.what==4){ int progress = msg.getData().getInt("progress"); pd.setMessage("已经下载"+String.valueOf(progress)+"%"); pd.setProgressStyle(ProgressDialog.STYLE_SPINNER); pd.show(); } if(msg.what==5){ Toast.makeText(MainActivity.this,"下载失败",Toast.LENGTH_SHORT).show(); } } };