3月 24, 2020 Android
### Android FileProvider

Android 使用 FileProvided 的時候,可能會遇到這個問題。

```text
FATAL EXCEPTION: main
Process: com.example.your.andrroidapp
java.lang.IllegalArgumentException: Failed to find configured root that contains /path/to/your.file
... error stacks
```

### 問題源因

遇到這個問題的原因,是因為沒有設定好 FileProvider 要存取的路徑。

假設在 `res/xml/file_paths.xml` 有以下內容 :

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

然後用以下的代碼運行 :

```java
// file from application directory
File mFile = new File(context.getFilesDir(), "myvideo.mp4");

// get uri via file provider
Uri mUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", mFile);
```

如果我們使用上面的代碼來取得檔案 URI 的話,就會出現錯誤。因為 `context.getFilesDir()` 對應的 XML 是 `files-path`,但是在 `res/xml/file_paths.xml` 內沒有相關的設定。

有關 file_paths 的設定可以參考這篇文章 : [Android FileProvider (API 24+)](https://cdn.19site.net/posts/117)

### 解決方法

修改一下上面的 XML 設定 :

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

再運行一次這段代碼 :

```java
// file from application directory
File mFile = new File(context.getFilesDir(), "myvideo.mp4");

// get uri via file provider
Uri mUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", mFile);

mUri.toString();
>>> content://com.example.fileprovider/files/myvideo.mp4
```

這樣就應該能成功運作了。
過去文章
2025 (9)
4 (5)
3 (1)
2 (3)
2024 (25)
11 (3)
10 (3)
9 (1)
3 (18)
2022 (6)
10 (1)
6 (2)
5 (1)
3 (1)
1 (1)
2021 (21)
11 (7)
7 (1)
6 (2)
5 (2)
4 (6)
3 (2)
2 (1)
2020 (92)
12 (1)
11 (2)
10 (4)
9 (10)
8 (5)
7 (1)
6 (3)
5 (1)
4 (4)
3 (25)
2 (7)
1 (29)
2019 (57)
12 (25)
11 (7)
9 (25)