I used to attach a logs file, that I was storing in externalCacheDir, to a mail client.
Using this : intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(logFile))
However, starting from Android 11 it just stopped working. So I tried using FileProvider. But once the mail client opens it says "Couldn't attach file".
I have tried doing everything I could find here on SO and on the internet in general. But I can't seem to find the solution that will actually work.
Activity :
val logFile: File = File(globalContext.externalCacheDir, "MyLogFile.log")
fun Activity.openMail(
type: String = "text/plain"
): Boolean {
val intent = Intent(Intent.ACTION_SENDTO)
intent.putExtra(Intent.EXTRA_EMAIL, arrayOf("<some address...>"))
intent.putExtra(Intent.EXTRA_SUBJECT, "Android Logs")
intent.putExtra(Intent.EXTRA_TEXT, "some text")
val uri = FileProvider.getUriForFile(this, "${BuildConfig.APPLICATION_ID}.fileprovider", logFile)
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
intent.type = type
intent.data = Uri.parse("mailto:")
if (intent.resolveActivity(packageManager) != null) {
startActivity(Intent.createChooser(intent, "Send email via::"))
return true
} else {
return false
}
}
Manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
provider_paths :
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-cache-path name="external_cache" path="."/>
</paths>