ava.io.IOException: открыть не удалось: EACCES (В доступе отказано)

Я использую ThinDownloadManager библиотека для скачивания видео с url, Необходимо сделать видео приватным, поэтому я люблю использовать internal storage для сохранения загружаемого видео, чтобы сделать его приватным. В приведенной выше библиотеке мы предоставляем две вещи: первая - это URL, а вторая - путь для хранения видеофайла. когда я даю внутренний путь, возникает исключение и вызывается метод onDownloadFailed видео.

Ниже мой код

public void startVideoDownloading() {
        //Show downloading in notification bar

        final NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle("Video downloading")
                .setContentText("Download in progress")
                .setSmallIcon(R.drawable.ic_notification);

        ThinDownloadManager downloadManager = new ThinDownloadManager();
        Uri downloadUri = Uri.parse(videoId);
        File fileDir = createDirectory();
        Uri destinationUri = Uri.parse(fileDir + uniqueId);
        DownloadRequest downloadRequest = new DownloadRequest(downloadUri)
                .setDestinationURI(destinationUri).setPriority(DownloadRequest.Priority.HIGH)
                .setDownloadListener(new DownloadStatusListener() {
                    @Override
                    public void onDownloadComplete(int id) {
                        Toast.makeText(Player.this, "Download Completed", Toast.LENGTH_SHORT).show();

                        mBuilder.setContentText(" Video download completed")
                                .setProgress(0, 0, false);
                        mNotifyManager.notify(id, mBuilder.build());

                    }

                    @Override
                    public void onDownloadFailed(int id, int errorCode, String errorMessage) {
                        Toast.makeText(Player.this, "Download Failed", Toast.LENGTH_SHORT).show();
                        mBuilder.setContentTitle("Failed");
                        mBuilder.setContentText("Downloading failed")
                                .setProgress(0, 0, false);
                        mNotifyManager.notify(id, mBuilder.build());

                    }

                    @Override
                    public void onProgress(int id, long totalBytes, long downloadedBytes, int progress) {
                        donutProgress.setProgress(progress);

                        mBuilder.setProgress(100, progress, false);

                        mNotifyManager.notify(id, mBuilder.build());

                    }
                });
        downloadManager.add(downloadRequest);
    }

    public File createDirectory() {
        File folder = new File(Environment.getDataDirectory() + "/+" + "downloadVideo/");
        if (!folder.exists()) {
            folder.mkdir();
            Log.d("TAG","Directory created");
        }else {
            Log.d("TAG","Directory exists");
        }
        return folder;

    }

ниже моя ошибка logcat

java.io.IOException: open failed: EACCES (Permission denied)
at java.io.File.createNewFile(File.java:946)
at com.thin.downloadmanager.DownloadDispatcher.transferData(DownloadDispatcher.java:213)
at com.thin.downloadmanager.DownloadDispatcher.executeDownload(DownloadDispatcher.java:142)
at com.thin.downloadmanager.DownloadDispatcher.run(DownloadDispatcher.java:81)
0Caused by: libcore.io.ErrnoException: open failed: EACCES (Permission denied)
at libcore.io.Posix.open(Native Method)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
at java.io.File.createNewFile(File.java:939)

Когда я предоставляю внешний путь хранения работает нормально. Как я могу решить эту проблему?

1 ответ

Скорее всего, вам нужно добавить следующую строку в манифест (как подробно описано здесь: https://developer.android.com/training/basics/data-storage/files.html)

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

Кроме того, если ваше приложение ориентировано на Android 6.0 или выше, вам нужно запросить это разрешение у пользователя во время выполнения - подробно здесь: https://developer.android.com/training/permissions/requesting.html

Другие вопросы по тегам