Share data
You can share a data with other app by sending Intent with the ACTION_SEND action.
share text
Optionally, you can add extras to include more information, such as email recipients.
- EXTRA_EMAIL - array of strings holding e-mail addresses that should be delivered to
- EXTRA_CC - array of strings holding e-mail addresses that should be carbon copied.
- EXTRA_BCC - array of strings holding e-mail addresses that should be blind carbon copied.
- EXTRA_SUBJECT - a string holding the desired subject line of a message
share binary data
Share binary data using the ACTION_SEND action. Set the appropriate MIME type and place a URI to the data in the extra EXTRA_STREAM.
The receiving application needs permission to access the data the Uri points to. The recommended ways to do this are:
- Store the data in your own ContentProvider, making sure that other apps have the correct permission to access your provider. To share files you can use FileProvider helper class.
- Use the system MediaStore
using file provider
Add a file provider to the Manifest.xml file. Set property grantUriPermissions to true. Also you need permission to write and read files.
In meta-data specify paths where files can be shared. Typically paths are specified in separate xml file. You can not add path programmatically.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.shareimage">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.shareimage.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/paths" />
</provider>
</application>
</manifest>
Add file res/xml/paths.xml with paths to your project.
?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path
name="shared_images"
path="images/" />
</paths>
Now just copy file to the specified path and get its URI.
// it is best to call this method in the background
// if you already have image file,
// just copy it to the File(getCacheDir(), "images") folder.
fun AppCompatActivity.getmageToShare(bitmap: Bitmap): Uri? {
var uri: Uri? = null
val imagefolder = File(getCacheDir(), "images")
imagefolder.mkdirs()
val file = File(imagefolder, "image_for_share.png")
runCatching {
FileOutputStream(file).use {
bitmap.compress(Bitmap.CompressFormat.PNG, 90, it)
it.flush()
uri = FileProvider.getUriForFile(this,
"com.example.shareimage.fileprovider",
file)
}
}.onFailure {
it.printStackTrace()
}
return uri
}