Как получить путь к файлу из содержимого URI для ZIP файла? - PullRequest
0 голосов
/ 17 октября 2019

Я вызываю намерение выбрать zip-файл и в onActivityResult он предоставляет мне URI контента. Например :: (content: //com.android.providers.downloads.documents/document/197). Выбранный файл находится в папке загрузки. Может ли кто-нибудь объяснить, как запросить распознаватель содержимого, чтобы получить путь к файлу? Спасибо.

Already tried code :- 

   Cursor cursor = getActivity().getContentResolver()
                .query(contentUri, null, null, null, null);

        try {
            if (cursor != null && cursor.moveToFirst()) {
            String path=cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                Log.i(TAG, "path  Name: " + path);
            }
           // NOTE :: Here I am getting the file name, But i want the file path.
        } finally {
            cursor.close();
        }

1 Ответ

0 голосов
/ 24 октября 2019

Я пробовал так много способов получить путь к файлу из выбранного файла в папке загрузки. Начиная с android Q, Google предложил SAF (Storage Access Framework) получить данные от пользователя. Мы не можем использовать Environment.getExternalStoragePublicDirectory (), чтобы получить путь к файлу от android Q и выше.

Для android Q и выше вы можете выполнить следующие шаги.

1) Начните намерение с действия или фрагмента, который вы хотите активировать.

Например:

public void performFileSearch() { //from developer docs

    // ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's file
    // browser.
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

    // Filter to only show results that can be "opened", such as a
    // file (as opposed to a list of contacts or timezones)
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    // Filter to show only images, using the image MIME data type.
    // If one wanted to search for ogg vorbis files, the type would be "audio/ogg".
    // To search for all documents available via installed storage providers,
    // it would be "*/*".
    intent.setType("application/pdf"); // MIME type for what file you required

    startActivityForResult(intent, READ_REQUEST_CODE);
}

2) Тогда результат появится наActivityResult вашего действияили фрагмент

@Override
public void onActivityResult(int requestCode, int resultCode,
        Intent resultData) { // from developer docs

    // The ACTION_OPEN_DOCUMENT intent was sent with the request code
    // READ_REQUEST_CODE. If the request code seen here doesn't match, it's the
    // response to some other intent, and the code below shouldn't run at all.

    if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        // The document selected by the user won't be returned in the intent.
        // Instead, a URI to that document will be contained in the return intent
        // provided to this method as a parameter.
        // Pull that URI using resultData.getData().
        Uri uri = null;
        if (resultData != null) {
            uri = resultData.getData();
            Log.i(TAG, "Uri: " + uri.toString());
            processWithUriToGetPath(uri);
        }
    }
}

Извлечение данных из URI (Примечание. Для изображений, видео и аудио вы можете обратиться к документу разработчика. Так как не нашел никакого подходящего документа для файла, приведя этот пример).

    private void processWithUriToGetPath(Uri contentUri) {
        //Use content Resolver to get the input stream that it holds the data and copy that in a temp file of your app file directory for your references
         File selectedFile = new File(getActivity().getFilesDir(), "your file name"); //your app file dir or cache dir you can use
       InputStream in = getActivity().getContentResolver().openInputStream(contentUri);
                 OutputStream out = new FileOutputStream(selectedFile);
                        try {
                            byte[] buf = new byte[1024];
                            int len;
                            if (in != null) {
                                while ((len = in.read(buf)) > 0) {
                                    out.write(buf, 0, len);
                                }
                                out.close();
                                in.close();
                            } catch (IOException ie) {
                            ie.printStackTrace();
                        }


 //after this you will get file from the selected file and you can do 
           whatever with your wish.
         // Hope it helps... 
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...