簡體   English   中英

如何在不使用 MANAGE_EXTERNAL_STORAGE 的情況下讀取 Android 11 中的 my.xml 文件?

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

所以我的文件夾結構是 Documents/XML/xml.xml

我在啟動應用程序時創建了 XML 文件夾。 然后用戶必須手動將他的 xml 文件放在那里。

在我的清單中,我有 READ 和 WRITE EXTERNAL STORAGE 權限。 我可以檢查.xml 文件是否存在,如果有則返回true,但是當我嘗試讀取和打印它時:打開失敗:EACCES(權限被拒絕)。

如何在不使用 Android 11 中的 MANAGE_EXTERNAL_STORAGE 的情況下繞過此問題?

從 Android 10 開始,每個新的 API 版本都會逐步撤銷舊的外部存儲權限。您需要使用新的共享存儲 API 來訪問外部存儲上的數據。 按照此處的說明進行操作

謝謝,如果有人想知道,這是我實現它的方式:

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();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM