我的应用程序对下载文件夹具有读写权限。如何调用默认应用程序打开文件并授予其读取文件的权限? 使用此代码时,默认应用程序将打开,但无法访问该文件:
public void openFile(String fileName)
{
String mimeType = URLConnection.guessContentTypeFromName(fileName);
Intent newIntent = new Intent(Intent.ACTION_VIEW);
Uri myUri = Uri.parse(fileName);
newIntent.setDataAndType(myUri, mimeType);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
newIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
try {
this.startActivity(newIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No handler for this type of file.", Toast.LENGTH_LONG).show();
}
}
例如,Acrobat Reader报告无法访问该文件。 仅GoogleFoto应用在打开时会征得其许可并成功打开图片。
答案 0 :(得分:0)
感谢CommonsWare
android / AndroidManifest.xml
<!-- file provider for open attached files-->
<provider android:name="android.support.v4.content.FileProvider" android:authorities="XXX.XXXXXXXXXXXX" android:exported="false" android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_provider_paths"/>
</provider>
android / res / xml / file_provider_paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path name="cache" path="/" />
<files-path name="files" path="/" />
</paths>
MainActivity.java
public String openFile(String filePath)
{
File file = new File(filePath);
if (!file.exists())
return "file not exist";
Uri uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID, file);
String mimeType = URLConnection.guessContentTypeFromName(filePath);
Intent newIntent = new Intent(Intent.ACTION_VIEW);
newIntent.setDataAndType(uri, mimeType);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
newIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
try {
this.startActivity(newIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No handler for this type of file.", Toast.LENGTH_LONG).show();
return "No handler for this type of file.";
}
return "";
}