由於FileProvider的變化,我必須修復Android N的應用程序。我已經基本閱讀了最後一篇關於這個話題的所有內容,但沒有找到解決方案爲我工作。使用FileProvider在Android N上打開下載的文件
下面是從我們的應用程序開始下載我們之前的代碼,並將其存儲於Download
文件夾,並調用一個ACTION_VIEW
意圖作爲soons爲DownloadManager
告訴他完成下載:
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Log.d(TAG, "Download commplete");
// Check for our download
long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (mDownloadReference == referenceId) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(mDownloadReference);
Cursor c = mDownloadManager.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
String localUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(localUri);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
if (mimeType != null) {
Intent openFileIntent = new Intent(Intent.ACTION_VIEW);
openFileIntent.setDataAndTypeAndNormalize(Uri.parse(localUri), mimeType);
openFileIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
mAcme.startActivity(openFileIntent);
}
catch (ActivityNotFoundException e) {
// Ignore if no activity was found.
}
}
}
}
}
}
};
這適用於Android男,但因受歡迎的FileUriExposedException
而在N上休息。我現在試圖通過使用FileProvider
來解決這個問題,但我無法實現它。當我嘗試獲取內容URI它打破:
Failed to find configured root that contains /file:/storage/emulated/0/Download/test.pdf
的localUri
從DownloadManager
返回的文件是:
file:///storage/emulated/0/Download/test.pdf
的Environment.getExternalStorageDirectory()
回報/storage/emulated/0
,這是代碼轉換:
File file = new File(localUri);
Log.d(TAG, localUri + " - " + Environment.getExternalStorageDirectory());
Uri contentUri = FileProvider.getUriForFile(ctxt, "my.file.provider", file);
從AndroidManifest.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="my.file.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
的file_paths.xml
:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_path" path="." />
</paths>
我已經嘗試了所有值我能找到該XML文件。 :(
確保你是在Android支持庫的最新版本。如果你是這樣的話,那麼感覺就像當前'FileProvider'中的一個錯誤。 – CommonsWare
'file:/// storage/emulated/0/Download/test.pdf'。你不能按原樣使用它。從中刪除「file://」。您必須使用有效的文件路徑:'/ storage/emulated/0/Download/test.pdf'。 – greenapps
@CommonsWare我在v24.2上運行。1 – althaus