javaandroidkotlinandroid-intentandroid-intent-chooser

How to open chooser intent of whats app and gmail only to send an attachment document in kotlin


I need to send the document created from my app to only gmail and whatsapp.

for whatsapp I got the working code,

        val filelocation = GlobalVariables.getMyFilePath(this, "dummy_file.mem")
        val uri = Uri.parse(filelocation.absolutePath)
        val whatsappIntent = Intent(Intent.ACTION_SEND)
        whatsappIntent.type = "text/plain"
        whatsappIntent.setPackage("com.whatsapp")
        whatsappIntent.putExtra(Intent.EXTRA_TEXT, "members file list")
        whatsappIntent.putExtra(Intent.EXTRA_STREAM, uri)
        whatsappIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

        this.startActivity(whatsappIntent)

based on this I just follwed the same for gmail. but the is not getting attached. it toast message file not attached

        val email = Intent(Intent.ACTION_SEND)
        email.setPackage("com.google.android.gm")
        email.putExtra(Intent.EXTRA_EMAIL, arrayOf<String>("vikas16acharya@gmail.com"))
        email.putExtra(Intent.EXTRA_SUBJECT, "members file list")
        email.putExtra(Intent.EXTRA_TEXT, message)
        email.putExtra(Intent.EXTRA_STREAM, uri)
        email.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        email.type = "message/rfc822"

        this.startActivity(email)

Solution

  • how to send attachment to gmail ?

    To send files you need some more things,

    first Inside Manifest->application add the below snippet

    <provider
                android:name="androidx.core.content.FileProvider"
                android:authorities="${applicationId}.provider"
                android:grantUriPermissions="true"
                android:exported="false">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/file_provider_paths" />
            </provider>
    

    then create a folder xml under res and add this file

    file_provider_paths.xml

    <?xml version="1.0" encoding="utf-8"?>
    <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
        <paths xmlns:android="http://schemas.android.com/apk/res/android">
            <external-files-path name="external_files" path="."/>
        </paths>
    </PreferenceScreen>
    

    then on your code add below line instead of val uri = Uri.parse(filelocation.absolutePath)

    val uri = FileProvider.getUriForFile(this, "${BuildConfig.APPLICATION_ID}.provider", filelocation)
    

    Now you can send attachments.

    how to show only whatsapp and gmail in chooser intent action ?

    refer this link https://stackoverflow.com/a/8550043/8750174