Skip to content

File usage under Android >= 11

File Provider

Accessing a file that is not in the application directory of the PTV Navigator is not possible for the PTV Navigator in Android versions >= 11. To enable accessing a file in the storage directory of a client app, the client software must use a FileProvider to grant access to that file that should be used by the PTV Navigator.

Steps to grant a permission is as following:

  • Create an xml file in the res/xml folder of your project and list all directories in your app namespace that should be able to be accessed from outside, see also the RITest app as an example.

    Example filepaths.xml:

        <paths xmlns:android="http://schemas.android.com/apk/res/android">
        <external-files-path name="myimages" path="images/"/>
        <external-files-path name="mybcr" path="."/>
        <external-files-path name="myimport" path="importPrefs/"/>
        </paths>
    
    Paths are all relative to the files directory of the client app.

  • Add a FileProvider to the manifest file (in the application section) and set the android:resource entry to the above created xml file

        <?xml version="1.0" encoding="utf-8"?>
        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        ... >
    
        <application
           .
           .
           .
            <provider
                android:name="androidx.core.content.FileProvider"
                android:authorities="com.example.fileprovider"
                android:exported="false"
                android:grantUriPermissions="true">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/filepaths" />
            </provider>
        </application>
    
    </manifest>
    
    Be sure to replace the android:authorities section with a valid name like 'your_package_name'.provider.

  • Create a file object with the file you want to transfer/share:

    File requestFile = new File(path, nameOfFile);
    

  • Create an uri for that file with FileProvider.getUriForFile():

    Uri fileUri = FileProvider.getUriForFile(getContext(), "com.example.fileprovider", requestFile);
    

  • Grant access permissions to this file for a specific package (here we use the navigator as the receiver) with getContext().grantUriPermission(). Use FLAG_GRANT_READ_URI_PERMISSION for minimal reading permission:

      getContext().grantUriPermission(BaseActivity.getForeignPackageName(), fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
    

  • If wanted, you can revoke the permission after the navigator sent back the response that the file was loaded (the navigator will copy the file to the navigator files directory (files with the same name will be overwritten) to be able to access it, and therefore it is save to revoke the permission after the navigator response).

    For more implementation details, please see the RITest demo app.