AndroidQ(10) 分区存储适配方法

创建文件夹

AndroidQ(10) 分区存储适配方法_第1张图片

下载文件

InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                OutputStream os = null;


                if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                    //储存下载文件的目录
                    File dir = new File(destFileDir);
                    Log.e("文件路径", "====" + dir.getPath());
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    file = new File(dir, destFileName);
                    fos = new FileOutputStream(file);
                    isQ = false;
                } else {
                    Uri uri = insertFileIntoMediaStore(destFileName);
                    os = resolver.openOutputStream(uri);
                    isQ = false;
                }

                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();

                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        if (isQ) {
                            os.write(buf, 0, len);
                        } else {
                            fos.write(buf, 0, len);
                        }
                        sum += len;
//                        int progress = (int) (sum * 1.0f / total * 100);
                        int progress = (int) (sum * 1.0f * 100 / apkSize);
                        //下载中更新进度条
                        listener.onDownloading(progress, total);
                    }
                    fos.flush();
                    //下载完成
                    listener.onDownloadSuccess(file);
                } catch (Exception e) {
                    listener.onDownloadFailed(e);
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {

                    }

                }

如果不想这么麻烦  只需要在manifest中添加   

android:requestLegacyExternalStorage = "true"

你可能感兴趣的:(Android)