Android os fileuriexposedexception exposed beyond app through clipdata item geturi

FileUriExposed Exception?

May 8, 2017 · 2 min read

Android may throw “ FileUriExposedException” in Android 7.0 (API level 24) and above,this exception will come when you will expose a file:// URIs outside your package domain through intent .

For apps targeting Android 7.0, the Android framework enforces the strict mode API policy that prohibits exposing file:// URIs outside your app. If an intent containing a file URI leaves your app, the app fails with a FileUriExposedException.

Your Exception will be like this:

So wondering how to avoid this exception then follow below steps:

Note:Considering you already given Runtime Permission for Camera and Storage.

You have to define a FileProvider for your app for that you have to give

element in your manifest see example.

Here authorities name should be unique thats why i used package name +.provider.

And the meta-data> child element of the

points to an XML file that specifies the directories you want to share.

Create file_provider_path.xml in the res/xml/ subdirectory of your project.

Here i am giving file name “example” of external storage.if your file path is in internal storage then you can give element in place of

Now for sending file:// uri to other app i will take example to open Camera App ,

For getting URI earlier we used to do like this

So we have to do like this now

check below example:

Ya that’s it,So FileProvider will return following URI

that is nothing but combination of these:

content://”android:authorities you give to provider in manifest”/” , you given in file_provider_path.xml”/”your fileName”

Welldone ! Your application should now work perfectly fine on any Android version including Android Nougat.

Источник

How to fix exposed beyond app through ClipData.Item.getUri

I was trying to build an application through which users can share complete screenshots of the current screen and share through the various apps.

While developing, I Stuck at the error exposed beyond app through ClipData.Item.getUri Due to that app gets crashed when I pressed on the Share Button.

Читайте также:  Почему нельзя удалить контакты с андроида

I have resolved this issue while debugging, and I thought it would be great To make an article and solve other user problems.

Fix the issue

This issue arises after Android SDK 24 or android 7.0. Before that, we are able to access file content using file:/// after 7.0, we have to use content:// which is a more secure way to access files.

To learn more, you can read the documentation. Without taking any further moment, let’s fix the above issue.

When we want to access file content outside the application storage, we need to use FileProvider.getUriForFile() method.

Open the Activity file and use the below code to get the URI of a file

Inside the parameter pass, the following code first parameter will accept the current activity details for that we have used this .

The second parameters are the authority where you need to provide app signature along with .provider

  • BuildConfig.APPLICATION_ID Show package name.
  • getLocalClassName() It will show the current activity class name.
  • .provider subclass of ContentProvider to access data

In the last parameter provide the path of Image file that you have already created prior to this .

Create path.xml

We need to create an XML path for that right click on the res folder and create a new Android Resource Directory, save the directory name with xml.

Under the xml directory, please create a new xml file save with file_path.xml, open it and add the below command

Add provider in AndroidManifest

Once you complete the above process Open AndroidManifest and add the below command inside the tag

android:authorities over here, use your application package name with class name where you have linked the URI along with .provider

Inside the tag on android: resources pass the above created xml file details.

Rest all, keep it the same as above and try to run applications, and you will not get the error if you follow the above steps correctly.

Wrap-up

That’s it to resolve exposed beyond app through ClipData.Item.getUri If the problem didn’t resolve, go through the article again.

If the problem still persists, use Pastebin and share your code with us we will try to fix it.

Please leave the comment If you found the article useful.

A man with a tech effusive, who has explored some of the amazing technology stuff and exploring more, While moving towards, I had a chance to work on Android Development, Linux, AWS, DevOps with several Open source tools.
One of my life mottos “Always be lifelong Students.”

Источник

android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/JPEG_20170403160746_742136310.jpg exposed beyond app through ClipData.Item.getUri() #41

Comments

yunhoi129 commented Apr 3, 2017

issue at API LEVEL 24

private File getImageFile() <
// Create an image file name
File imageFile = null;
try <
String timeStamp = new SimpleDateFormat(«yyyyMMddHHmmss», Locale.getDefault()).format(new Date());
String imageFileName = «JPEG_» + timeStamp + «_»;
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

Читайте также:  Режим разработчика андроид honor

i think.. Uri.fromFile should be changed to like below

FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + «.provider», createImageFile());

The text was updated successfully, but these errors were encountered:

yunhoi129 commented Apr 3, 2017

Sorry. it’s my fault i used low version.. thx.

ParkSangGwon commented Apr 27, 2017

sivabramha commented Mar 15, 2018 •

Using getactivity().getExternalFilesDir(null).getAbsolutePath() we can solve your problem

parshwa1596 commented Jan 23, 2020

android.os.FileUriExposedException: file:///storage/emulated/0/Documents/Patidar.pdf exposed beyond app through Intent.getData()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1960)
at android.net.Uri.checkFileUriExposed(Uri.java:2362)
at android.content.Intent.prepareToLeaveProcess(Intent.java:9901)
at android.content.Intent.prepareToLeaveProcess(Intent.java:9853)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1612)
at android.app.Activity.startActivityForResult(Activity.java:4555)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
at android.app.Activity.startActivityForResult(Activity.java:4513)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
at android.app.Activity.startActivity(Activity.java:4874)
at android.app.Activity.startActivity(Activity.java:4842)
at com.patidar.marriagebureau.Activities.Printprofile.previewPdf(Printprofile.java:501)
at com.patidar.marriagebureau.Activities.Printprofile.createPdf(Printprofile.java:486)
at com.patidar.marriagebureau.Activities.Printprofile.createPdfWrapper(Printprofile.java:416)
at com.patidar.marriagebureau.Activities.Printprofile.access$000(Printprofile.java:65)
at com.patidar.marriagebureau.Activities.Printprofile$1.onClick(Printprofile.java:171)
at android.view.View.performClick(View.java:6312)

i got these error what can i do?

abdullaabdulla422 commented Jul 6, 2020

you need to add provider in your manifest

momodu commented Jan 18, 2021

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

android.os.FileUriExposedException: file:///storage/emulated/0 exposed beyond app through ClipData.Item.getUri() in android 7 #204

Comments

kikani89 commented Apr 10, 2017

vq3.glassframe.quickcode.com.glassframe W/System.err: android.os.FileUriExposedException: file:///storage/emulated/0/bichooser/1491833482318.jpg exposed beyond app through ClipData.Item.getUri()
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.net.Uri.checkFileUriExposed(Uri.java:2346)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.content.ClipData.prepareToLeaveProcess(ClipData.java:845)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.content.Intent.prepareToLeaveProcess(Intent.java:8941)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.content.Intent.prepareToLeaveProcess(Intent.java:8926)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.app.Instrumentation.execStartActivity(Instrumentation.java:1517)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.app.Activity.startActivityForResult(Activity.java:4225)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.support.v4.app.ActivityCompatJB.startActivityForResult(ActivityCompatJB.java:30)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.support.v4.app.ActivityCompat.startActivityForResult(ActivityCompat.java:146)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:937)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.support.v4.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:1047)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.support.v4.app.Fragment.startActivityForResult(Fragment.java:959)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.support.v4.app.Fragment.startActivityForResult(Fragment.java:948)
vq3.glassframe.quickcode.com.glassframe W/System.err: at com.kbeanie.imagechooser.api.BChooser.startActivity(BChooser.java:159)
vq3.glassframe.quickcode.com.glassframe W/System.err: at com.kbeanie.imagechooser.api.ImageChooserManager.takePicture(ImageChooserManager.java:251)
vq3.glassframe.quickcode.com.glassframe W/System.err: at com.kbeanie.imagechooser.api.ImageChooserManager.choose(ImageChooserManager.java:217)
vq3.glassframe.quickcode.com.glassframe W/System.err: at vq3.glassframe.quickcode.com.glassframe.StartFragment.takePicture(StartFragment.java:108)
vq3.glassframe.quickcode.com.glassframe W/System.err: at vq3.glassframe.quickcode.com.glassframe.StartFragment.access$100(StartFragment.java:40)
vq3.glassframe.quickcode.com.glassframe W/System.err: at vq3.glassframe.quickcode.com.glassframe.StartFragment$1.onNavigationItemSelected(StartFragment.java:68)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:184)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.support.design.internal.BottomNavigationMenuView$1.onClick(BottomNavigationMenuView.java:90)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.view.View.performClick(View.java:5637)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.view.View$PerformClick.run(View.java:22429)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.os.Looper.loop(Looper.java:154)
vq3.glassframe.quickcode.com.glassframe W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
vq3.glassframe.quickcode.com.glassframe W/System.err: at java.lang.reflect.Method.invoke(Native Method)
vq3.glassframe.quickcode.com.glassframe W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
vq3.glassframe.quickcode.com.glassframe W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

The text was updated successfully, but these errors were encountered:

kikani89 commented Apr 11, 2017

solved check out this.
kikani89 / image-chooser-library

tvats1988 commented Aug 3, 2017

Just paste the below code in activity onCreate()

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build());

It will ignore URI exposure

ajitdubey-mob-ibtech commented Aug 17, 2017

@tvats1988 i think it is workaround not a good solutions. is it?

Источник

Исключение FileUriExposedException в Android

мне нужно открыть папку во внутреннем хранилище, которое содержит изображения.

Я использую следующий код.

Читайте также:  Что такое чистая установка андроид

Java

пути

Манифест

xml / file_paths

фатальное исключение: основной процесс: android.приложения.БНБ.компания.myphotos, PID: Двадцать две тысячи четыреста восемьдесят два андроид.ОС.FileUriExposedException: файл: / / / хранение / эмулируется / 0 / фотографии/MyPhotos подвергаются за пределами приложения через намерение.getData ()

есть ли другой способ открыть папку во внутреннем хранилище? Спасибо!

обновление #1

и ошибка ушедший.

в любом случае я должен выбрать всегда приложение, чтобы открыть эту папку.

есть ли возможность использовать приложение «Мои файлы» по умолчанию для открытия определенной папки?

3 ответов

есть ли возможность использовать приложение «Мои файлы» по умолчанию для открытия определенной папки?

Да И Нет. Его не 100% гарантировано, что он будет работать на всех устройствах.

Edit 1:

Ниже приведен один из способов с помощью которого это можно сделать. Я тестировал на нескольких эмуляторах (под управлением Android N & Android O) и загружает файл по умолчанию исследователь:

MainActivity.java

AndroidManifest.xml

GenericFileProvider.java

file_paths.xml

вышеуказанный подход не работает на больших игроках, таких как samsung

варианты

1. Использование типа DocumentsContract.Document.MIME_TYPE_DIR

этот подход работает на несколько эмуляторов и ограниченный набор устройств. Он не работает с крупными игроками, такими как Samsung или Huawei.

2. Использование типа resource/folder

этот подход работает, только если пользователь установил приложение ES file explorer.

если вы решили использовать, то вы должны проверить, если какой-либо намерение доступно для обработки его с помощью:

диспетчер пакетов диспетчера пакетов = getActivity().getPackageManager();

3. Использование типа */*

этот подход работает, если пользователь выбирает приложение файлового менеджера из выбора намерения и отмечает его как приложение по умолчанию для обработки */* . Однако у него есть некоторые недостатки (Благодаря @CommonsWare для выведения некоторых из них):

  • этот тип загрузит все приложения на устройстве и позволит пользователю выбрать один из них для завершения действие.
  • если нет проводника файлов и пользователь выбирает другие приложения для загрузки вашего намерения, то другое приложение рухнет или просто покажет черный экран. Например. Вы используете галерею или другое приложение, чтобы запустить его, а не проводник, то Галерея приложение будет либо сбой или показать черный экран.
  • даже если есть проводник, но пользователь решает использовать другие приложения, другие приложения могут сбой

4. Использование типа text/csv

это ограничит количество приложений, которые будут отображаться пользователю, но те же ограничения, когда используется. Приложения, которые могут обрабатывать csv будет отображаться, и если пользователь выберет его, то приложения будут сбой.

есть некоторые устройства конкретных реализаций доступны здесь как отметил @Academy of Programmer что требует определения намерения файлового менеджера по умолчанию и дополнительная потребность им.

вывод:

нет стандартного типа для его достижения, поскольку на данный момент нет стандарта, за которым следуют файловые менеджеры для поддержки определенного типа. В будущем, возможно, Google придумает какой-то подход. Лучшей альтернативой было бы реализовать свой собственный файловый менеджер, как это делает Dropbox или Google Drive. Существует несколько библиотек, которые предоставляют эту функцию.

Источник

Оцените статью