簡體   English   中英

從我剛剛創建的文件中獲取Uri(android)

[英]Get Uri from file I just created (android)

原諒我可能是一個愚蠢的問題,但我真的找不到任何答案。

我需要我的程序將EditText的內容保存為html文件並與其他應用程序共享。 為此,我需要將文件寫入內部存儲,然后獲取URI。 但是,在任何地方(我都可以)沒有關於如何做到這一點的信息。

這是我的代碼(編輯器是Activity的名稱,myapp是包的名稱):

String filename = "Lorem ipsum.html";

            FileOutputStream outputStream;

            try {
                outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
                outputStream.write(Html.toHtml(textField.getText()).getBytes());
                outputStream.close();
                System.out.println(filename);
            } catch (Exception e) {
                e.printStackTrace();
            }

                Intent shareIntent = ShareCompat.IntentBuilder.from(Editor.this)
                        .setStream(FileProvider.getUriForFile(Editor.this, "com.myapp.fileprovider", new File(filename)))
                        .getIntent();
                shareIntent.setData(FileProvider.getUriForFile(Editor.this, "com.myapp.fileprovider", new File(filename)));
                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(shareIntent);

據我所知,文件創建部分工作得很好; 沒有例外被捕獲。 但是,實際共享部分崩潰時出現此錯誤:

java.lang.IllegalArgumentException: Failed to find configured root that contains /Lorem ipsum.html

我在嘗試查找URI時顯然做錯了,但我一直無法找到解決方案。 官方文檔后沒有幫助,我找不到這個具體問題的例子。

如果重要,這是我的fileprovider聲明:

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.myapp.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/paths" />
    </provider>

預先感謝您的任何幫助。

在你的代碼中:

FileProvider.getUriForFile(Editor.this, "com.myapp.fileprovider", new File(filename))

第三個參數相當於:

new File("Lorem ipsum.html"");

這是無效的。

您應該使用文件的完整路徑作為File的構造函數中的參數。

正如@Fatih評論你應該使用

new File(getFilesDir(), filename)

作為第三個參數。

此外,清單中的authorities參數應更正為:

android:authorities="${applicationId}.provider" 

所以你的最終陳述將是:

Uri uri= FileProvider.getUriForFile(Editor.this,
        getApplicationContext().getPackageName() + ".provider",
        new File(Editor.this.getFilesDir(), filename));

在res / xml文件夾路徑文件中更改:

<?xml version="1.0" encoding="utf-8"?> <paths> <files-path name="files" path="." /> </paths><!-- NOT THIS: <external-path name="external_files" path="."/>-->

如果清單中的權限參數是:

android:authorities="${applicationId}.provider"

並在java代碼中:

File file = new File(context.getFilesDir(), fileName);
Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);

暫無
暫無

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

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