【发布时间】:2017-02-21 03:08:32
【问题描述】:
由于 FileProvider 的更改,我必须修复我们的 Android N 应用程序。我基本上已经阅读了上一篇关于这个主题的所有内容,但没有找到适合我的解决方案。
这是我们之前的代码,它开始从我们的应用程序下载,将它们存储在 Download 文件夹中,并在 DownloadManager 告诉他下载完成后立即调用 ACTION_VIEW 意图:
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 M,但由于流行的FileUriExposedException 而在 N 上中断。我现在尝试使用FileProvider 来解决这个问题,但我无法让它工作。当我尝试获取内容 URI 时,它崩溃了:
Failed to find configured root that contains /file:/storage/emulated/0/Download/test.pdf
从文件的DownloadManager 返回的localUri 是:
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中的一个错误。 -
file:///storage/emulated/0/Download/test.pdf。您不能按原样使用它。从中删除“file://”。您必须使用有效的文件路径:/storage/emulated/0/Download/test.pdf。 -
@CommonsWare 我在 v24.2.1 上运行
-
@greenapps 你救了我的命!我真的很讨厌官方文档中简化的代码示例。 ://
-
什么是
mDownloadReference?
标签: android android-fileprovider android-7.0-nougat