Gmail file attachment fails with empty file error on Android 6.0+

I’m having trouble with my Android app that handles file attachments for Gmail. The app used to work perfectly before Android 6.0, but now it’s throwing an error.

What my code does:

String filePath = Environment.getExternalStorageDirectory() + "/media.mp4";
File mediaFile = new File(filePath);
Uri fileUri = Uri.fromFile(mediaFile);
Intent result = new Intent();
result.setData(fileUri);
setResult(Activity.RESULT_OK, result);
finish();

The problem: When Gmail tries to attach the file, I get this message: Can’t attach empty file

I noticed that ES File Explorer has two options when sharing files:

  • Normal Android Way (works with Gmail)
  • File Way (fails like my app)

What’s the difference between these approaches? How can I implement the “Normal Android Way” in my code?

I’ve tried using putExtra(EXTRA_STREAM, filePath) multiple times but it doesn’t work. Any ideas on how to fix this attachment issue?

u might be dealing with scoped storage issues. since android 7, Uri.fromFile() isn’t allowed. try using FileProvider in ur manifest, and replace it with FileProvider.getUriForFile(). oh, and make sure to add FLAG_GRANT_READ_URI_PERMISSION for access.