Share pdf file or Image file using kotlin code example
Share pdf file or Image file using various other application in android Kotlin with code
Starting from Android version 7.0 (API level 24) and higher, the file:// URI scheme is no longer supported for sharing files between apps due to security reasons. Instead, we use a FileProvider to share files with other apps.
Otherwise we got error:
FATAL EXCEPTION: main
Process: com.nipa.xlsheetcreate, PID: 11878
android.os.FileUriExposedException: file:///storage/emulated/0/createXLSheet/06-15-23-14-28_document.pdf exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:2141)
For solving error we using provider , let’s check below code for sharing a file
Add in manifest file
for permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Create a xml file in : res/xml/
provider_paths.xml
Add code below:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>
Then in manifest file write below code:
<application
…>
<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>
Then Activity page write below function and share file :
private fun sharePDFFile(file:File ) {
val URI = FileProvider.getUriForFile(
this@MainActivity,
BuildConfig.APPLICATION_ID + ".provider",
file
)
val intent = Intent(Intent.ACTION_SEND)
intent.type = "application/pdf"
intent.putExtra(Intent.EXTRA_STREAM, URI)
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
startActivity(Intent.createChooser(intent, "Share PDF"))
}
Comments
Post a Comment