Rectifying FileUriExposedException

If we use the code

Uri imageuri = Uri.fromFile(new java.io.File(_path));

It will cause FileUriExposedException if the file:// Uri is exposed to another app. You cannot use uri.fromFile(File) in new versions of android because it causes file uri exposed exception.


You have to use File provider.


If you are using Sketchware:
1. First Add Camera Component.

2. Then use following code:
Uri imageUri = FileProvider.getUriForFile(MainActivity.this, getApplicationContext().getPackageName() + ".provider", new java.io.File(_path));


If you are using android studio
1. Put following code in AndroidManifest.xml:
<provider android:name="androidx.core.content.FileProvider" android:authorities="com.xxxx.xxxx.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"/> </provider>

Replace com.xxxx.xxxx in code above with package name of your app.

2. In folder app/src/main/res/ create a folder 'xml'. Then in folder app/src/main/res/xml add a file provider_paths.xml. In provider_paths.xml, put following code:
<paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="external_files" path="."/> </paths>

3. Then use following code:
Uri imageUri = FileProvider.getUriForFile(MainActivity.this, getApplicationContext().getPackageName() + ".provider", new java.io.File(_path));


Comments

  1. Your blog is awfully appealing. I am contented with your post. I regularly read your blog and its very helpful. If you are looking for the best Api Integration, then visit Neebal. Thanks! I enjoyed this blog post.

    ReplyDelete

Post a Comment

Popular posts from this blog

A Flash Light App in Sketchware

Firebase auth in Sketchware for Login Activity

Simple car racing android game in Sketchware

Create a PDF reader android App in Sketchware

Easiest way to create an App for your website