首页 > 解决方案 > 当我尝试创建文件时权限被拒绝 - Android8+ - 系统模式下的应用程序

问题描述

我正在开发一个以系统模式安装的应用程序。他像 Google Play、Facebook、Email 一样出厂安装......该应用程序通过下载管理器下载一个 zip 文件,如下所示:

DownloadManager.Request request = new DownloadManager.Request(uri);     
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);      request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(context, destination, filename + fileextention);

目的地是 DIRECTORY_DOWNLOADS;

然后我做文件的解压缩:

cr = context.getContentResolver();
        try {
            zis = new ZipInputStream(new BufferedInputStream(cr.openInputStream(Uri.parse(sourceFile))));
            //zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceFile)));
            ZipEntry ze;
            int count;

            byte[] buffer = new byte[BUFFER_SIZE];
            while ((ze = zis.getNextEntry()) != null) {

                String fileName = ze.getName();

                fileName = fileName.substring(fileName.indexOf("/") + 1);
                File file = new File(destinationFolder, file_name);

                File dir = ze.isDirectory() ? file : file.getParentFile();
                Log.i("MainService", "Unzipping fileName: " + fileName);

                file_path = destinationFolder + "/" + fileName;

                if (!dir.isDirectory() && !dir.mkdirs())
                    throw new FileNotFoundException("Invalid path: " + dir.getAbsolutePath());
                if (ze.isDirectory()) continue;
                FileOutputStream fout = new FileOutputStream(file);
                try {
                    while ((count = zis.read(buffer)) != -1) {
                        fout.write(buffer, 0, count);
                    }

                } finally {
                    fout.close();
                }

                list_filenames.add(file_downloaded);

            }
        } catch (IOException ioe) {
            Log.d("MainService", "Error catch: " + ioe.getMessage());
            return list_filenames;
        } finally {
            if (zis != null)
                try {
                    zis.close();
                } catch (IOException e) {

                }
        }

这就是问题所在。在 While 的第一次循环后,我得到了 Permission Denied。我在 zip 中取第一个文件名,然后应用程序转到 Catch ( Log.d("MainService", "Error catch: " + ioe.getMessage())) 并拒绝权限,并且 Unzip 方法停止。

我在想,当我的应用程序以系统模式安装时,他们不需要用户权限。顺便说一句..这是我的清单:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

你能帮我吗?谢谢。

标签: androidpermissionsandroid-8.0-oreo

解决方案


第一的。在运行时询问权限。第二。您需要添加一些代码。对于最新的Android版本,这还不够Uri.parse(sourceFile) 这篇文章会帮助你


推荐阅读