简体   繁体   中英

How can I read my .xml file in Android 11 without using MANAGE_EXTERNAL_STORAGE?

So my folder structure is Documents/XML/xml.xml

I create the XML folder upon starting the app. The user then has to put there his xml file manually.

In my manifest I have READ and WRITE EXTERNAL STORAGE permissions. I can check if the.xml file exists and it returns true if there is any, but when I try to read and print it: open failed: EACCES (Permission denied).

How can I bypass this without using MANAGE_EXTERNAL_STORAGE in Android 11?

The old external storage permission have been progressively revoked with every new API release, starting with Android 10. You'll need to use the new shared storage API to access data on external storage. Follow the instructions here

Thanks, if anyone is wondering, here is how I implemented it:

private void openFile(Uri pickerInitialUri) {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("text/xml");

        // Optionally, specify a URI for the file that should appear in the
        // system file picker when it loads.
        intent.putExtra("android.provider.extra.EXTRA_INITIAL_URI", pickerInitialUri);

        startActivityForResult(intent, 200);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                 Intent resultData) {
        if (requestCode == 200
                && resultCode == Activity.RESULT_OK) {
            // The result data contains a URI for the document or directory that
            // the user selected.
            Uri uri = null;
            if (resultData != null) {
                uri = resultData.getData();
                // Perform operations on the document using its URI.
                try {
                    System.out.println(readXMLFromUri(uri));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String readXMLFromUri(Uri uri) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        try (InputStream inputStream =
                     getContext().getContentResolver().openInputStream(uri);
             BufferedReader reader = new BufferedReader(
                     new InputStreamReader(Objects.requireNonNull(inputStream)))) {
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        }
        return stringBuilder.toString();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM