Skip to content

Instantly share code, notes, and snippets.

@omkar-tenkale
Last active November 20, 2022 23:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omkar-tenkale/34d3aa1966653e6949d1ddaee1ba3355 to your computer and use it in GitHub Desktop.
Save omkar-tenkale/34d3aa1966653e6949d1ddaee1ba3355 to your computer and use it in GitHub Desktop.
android FileUriExposedException fix view file intent crash with fileprovider approach
package com.myapp;
import androidx.core.content.FileProvider;
//(Place anywhere,put same path in manifest relative to package) GenericFileProvider.java
public class GenericFileProvider extends FileProvider {
}
<provider
android:name=".GenericFileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
public static boolean openFile(Context context, String filepath) {
Uri uri;
if(Build.VERSION.SDK_INT< Build.VERSION_CODES.N){
uri = Uri.fromFile(new File(filepath));
}else {
uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, new File(filepath));
}
return openUri(context, uri);
}
public static boolean openUri(Context context, Uri uri) {
return openUri(context, getOpenIntent(uri, context.getContentResolver().getType(uri)));
}
public static boolean openUri(Context context, Intent intent)
{
try {
context.startActivity(intent);
return true;
} catch (Throwable e) {
Log.d("open file", String.format(Locale.US,
"Open uri request failed with error message '%s'",
e.getMessage()));
}
return false;
}
public static Intent getOpenIntent(Uri url, String type) {
return new Intent( geActionTypeToView(type)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION).setDataAndType(url, type);
}
FileUtil.openFile(activity,fileToOpen.getAbsolutePath())
//Put in /app/src/main/res/xml/provider_paths.xml << DELETE THIS LINE
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<files-path
name="files"
path="." />
</paths>
@J-Srinivasalu
Copy link

unresolved reference getActionTypetoView(), how to resolve this error

@oluwabajio
Copy link

@J-Srinivasalu use return new Intent( Intent.ACTION_VIEW).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION).setDataAndType(url, type);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment