Reputation: 7070
I am trying to share file with email clients and Google Drive. Now, in following code, only Google drive is opening and email clients are not opening at all. I can provide equivalent Java code of following code if required
val photoURI: Uri = FileProvider.getUriForFile(this, "com.emerson.oversight.com.emerson.oversight.provider",
File(this.cacheDir.path + "/SensorReport.pdf"))
val emailIntent = Intent(Intent.ACTION_SENDTO)
emailIntent.data = Uri.parse("mailto:")
emailIntent.putExtra(Intent.EXTRA_STREAM, photoURI)
emailIntent.putExtra(Intent.EXTRA_EMAIL, "[email protected]")
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "dsadsada")
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
val driveIntent = Intent()
driveIntent.`package`= "com.google.android.apps.docs"
driveIntent.action = Intent.ACTION_VIEW
val fileID = File(this.cacheDir.path + "/SensorReport.pdf")
val url = "https://docs.google.com/file/d/" + fileID
driveIntent.data = Uri.parse(url)
val openInChooser = Intent.createChooser(driveIntent, getString(R.string.share_using))
openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayListOf(emailIntent))
startActivity(openInChooser)
Please help
Upvotes: 0
Views: 1306
Reputation: 11321
You were almost there, the only missing piece in the puzzle is the getPackageManager().queryIntentActivities
method that will return all activities that can handle your email intent. With the ResolveInfo returned you can build an intent for each email option to be displayed in the chooser. Then you can pass the array of those intents as Intent.EXTRA_INITIAL_INTENTS
. You could even exclude certain packages if you like here. So the final part of your code would look something like this:
val openInChooser = Intent.createChooser(driveIntent, getString(R.string.share_using))
val emailOptionIntents = mutableListOf<Intent>()
val resInfo = getPackageManager().queryIntentActivities(emailIntent, 0)
if (!resInfo.isEmpty()) {
for (resolveInfo in resInfo) {
val emailOptionIntent = Intent(Intent.ACTION_SENDTO)
emailOptionIntent.data = Uri.parse("mailto:")
emailOptionIntent.putExtra(Intent.EXTRA_STREAM, photoURI)
emailOptionIntent.putExtra(Intent.EXTRA_EMAIL, "[email protected]")
emailOptionIntent.putExtra(Intent.EXTRA_SUBJECT, "dsadsada")
emailOptionIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
emailOptionIntent.`package` = resolveInfo.activityInfo.packageName
emailOptionIntents.add(emailOptionIntent)
}
}
openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, emailOptionIntents.toTypedArray())
startActivity(openInChooser)
Upvotes: 1