Search code examples
androidandroid-install-apkandroid-fileprovider

Update app using Intent fails with FileUriExposedException


I am trying to update my application using the following code:

File outputFile = ...;

Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(outputFile), "application/vnd.android.package-archive");
promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
promptInstall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
this.context.startActivity(promptInstall);

I have set all file provider requirements:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths" />
</provider>

and provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="downloads" path="."/>
</paths>

When I run this code I get the following error on startActivity line:

android.os.FileUriExposedException: file:///storage/emulated/0/Download/app-release.apk exposed beyond app through Intent.getData()

I looked around Stackoverflow and google, but none of the solutions worked. Am I doing someting wrong in provider_paths.xml?


Solution

  • I think you are missing Intent.FLAG_GRANT_WRITE_URI_PERMISSION, it will grant rights to the component that eventually handles the request and its Intent.

    Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(outputFile), "application/vnd.android.package-archive");
    promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    promptInstall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    this.context.startActivity(promptInstall);
    

    And change

    Uri uri = Uri.fromFile(outputFile);
    

    to

    Uri uri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider",outputFile); 
    

    Hope this will solve your issue...

    Read more about this in commonsware blog. It has been has explained clearly on this : https://commonsware.com/blog/2016/08/31/granting-permissions-uri-intent-extra.html