Skip to content Skip to sidebar Skip to footer

Open File In Cache Directory With Action_view

I have been searching for this for a while now but it I can't make this to work correctly. Let me explain. I have an android application that saves files (images, documents, ...) i

Solution 1:

I found out that I had to do things differently.

Instead of creating my own ContentProvider, the v4 support library offers a FileProvider class that can be used.

In AndroidManifest.xml add

<application...><providerandroid:name="android.support.v4.content.FileProvider"android:authorities="be.myapplication"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/file_paths" /></provider></application>

The FILE_PROVIDER_PATHS is an xml file that describes which files can be read by other applications.

So I added a file_paths.xml file to the res/xml folder.

<pathsxmlns:android="http://schemas.android.com/apk/res/android"><cache-pathname="my_cache"path="." /></paths>

And the only thing you have to do then is create and start the intent to show the file.

Filefile=newFile(getCacheDir(), "test.pdf");

Uriuri= FileProvider.getUriForFile(context, "be.myapplication", file);

Intentintent=newIntent();
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(uri, "application/pdf");

startActivity(intent);

And actually that's it.

IMPORTANT: Please do not forget setting FLAG_GRANT_READ_URI_PERMISSION flags for the intent. Otherwise it will not work.

Post a Comment for "Open File In Cache Directory With Action_view"