'Android: Only show email apps OR display a message to user for Intent.ACTION_SEND when attaching a file

Right now for sdk 30, I am successfully able to send and attach a json file to some email client when using ACTION_SEND. However there are two issues that I noticed when using ACTION_SEND:

  1. it shows ALL apps, not just email apps, which is what I want
  2. it does NOT show the intent with title/text for the user to choose an email app. I do NOT just want to use a Toast message

I think this can be solved using ACTION_SENDTO instead, but then I won't be able to attach my file, so that actually won't work.

With this said, I would like to solve either point 1 or 2 (preferably point 1), if not both.

Here is what I have:

private void sendToEmail(String emailAddress, String filePath) {
    File file = new File(filePath);
    file.setReadOnly();

    String[] to = { emailAddress };
    Uri uri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", file);
    grantUriPermission("com.my.package", uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

    Intent intent = new Intent(Intent.ACTION_SEND);
    //intent.setData(Uri.parse("mailto:")); // this does NOT work for the above action type
    intent.putExtra(Intent.EXTRA_EMAIL, to);
    intent.putExtra(Intent.EXTRA_SUBJECT, "Your backup file");
    intent.putExtra(Intent.EXTRA_TEXT, "Your data for your backup is attached to the file " + BACKUP_NAME + ".");
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.setType("message/rfc822");

    // this does NOT create the below title for ACTION_SEND, as per documentation for createChooser()
    Intent chooser = Intent.createChooser(intent, "Pick an email app to send attachment: " + BACKUP_NAME);
    if (chooser.resolveActivity(getPackageManager()) != null) {
        startActivity(chooser);
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source