The chat opened but the PDF wasn't attached: Android share grants die with the receiving screen
Disclosure: I'm the developer of QuickDial, and this post is published from my account. It was drafted and published by an AI agent working on my behalf from the app's source code. QuickDial is an independent app, not af
Disclosure: I'm the developer of QuickDial, and this post is published from my account. It was drafted and published by an AI agent working on my behalf from the app's source code. QuickDial is an independent app, not affiliated with WhatsApp LLC or Meta.
QuickDial has a Share as PDF button: select photos in a chat and they become one PDF, each photo's caption printed under it. The app then opens the system share sheet and the person picks where it goes.
The bug report was short: "PDF shared to an AI chat app opens the chat but the file is not attached." Photos shared the same way arrived fine. The PDF, and documents such as a DWG or an XLSX picked from the chat folder, did not.
This post is about why, and the fix that shipped: hand out only your own copy, grant it to the receiving packages directly, and clean the copies up on a timer.
The usual share code, and what it assumes
The textbook version looks like this:
val uri = FileProvider.getUriForFile(this, authority, pdfFile)
val send = Intent(Intent.ACTION_SEND).apply {
type = "application/pdf"
putExtra(Intent.EXTRA_STREAM, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
startActivity(Intent.createChooser(send, "Share PDF"))
FLAG_GRANT_READ_URI_PERMISSION gives read access to the activity that receives the intent. That word matters. The grant is tied to that activity, the app's share screen, not to the app as a whole.
Many apps have a small share screen that takes the file, then starts their real chat or compose screen and finishes itself. When the share screen goes, the grant can go with it. The chat screen then tries to read a content:// URI it no longer has access to, fails quietly, and opens empty.
Why photos survived
Photos from the gallery are in the media store. A receiving app that holds media permissions can often read them through its own access, so the lost grant does not matter. A PDF in your app's cache, or a document from a folder the user granted to you through the folder picker, has no second route. The grant is the only way in.
So "photos work, PDFs don't" was not about file type. It was about whether the receiver had any access of its own.
Fix 1: only ever hand out your own copy
Before, a picked document went out as the original content:// URI from the user's folder. That URI belongs to a grant our app holds, and we cannot pass that grant on to another app.
Now every document is copied into a per-share folder in our cache and served by our own FileProvider, with its real display name and MIME type:
fun copyIn(context: Context, src: Uri, stamp: String, index: Int): File? {
val resolver = context.contentResolver
val mime = resolver.getType(src)
val display = resolver.query(src, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
?.use { c -> if (c.moveToFirst() && !c.isNull(0)) c.getString(0) else null }
val dir = File(File(context.cacheDir, "share_out"), "$stamp-$index").apply { mkdirs() }
val out = File(dir, safeName(display, mime, "file-${index + 1}"))
resolver.openInputStream(src)?.use { input -> out.outputStream().use { input.copyTo(it) } } ?: return null
return out
}
Two details turned out to matter:
-
A folder per item. Two files called
quote.pdffrom different chats must not overwrite each other.share_out/<stamp>-<index>/quote.pdfkeeps the real name, which the receiving app shows to the person. -
The name is cleaned and the extension added.
safeNamekeeps only the last path segment, drops characters some file systems refuse (: * ? " < > |), strips leading dots, caps the length at 120 characters while keeping the extension, and adds an extension from the MIME type when there is none. A receiver that decides what to do from the extension gets a file it understands.
The FileProvider paths file names exactly two cache folders and nothing else:
<paths>
<cache-path name="album_pdf" path="album_pdf/" />
<cache-path name="share_out" path="share_out/" />
</paths>
The user's original file is only read, never moved or changed.
Fix 2: grant the packages, not just the activity
Context.grantUriPermission(packageName, uri, flags) gives read access to a package. It is not tied to whichever screen happens to be in front, so it outlives the share screen closing.
Before the share sheet opens, we don't know which app the person will pick. So the grant goes to every app that can receive this share:
fun grantToReceivers(context: Context, send: Intent, uris: List<Uri>): Int {
val packages = context.packageManager
.queryIntentActivities(send, PackageManager.MATCH_DEFAULT_ONLY)
.mapNotNull { it.activityInfo?.packageName }
.filter { it != context.packageName }
.distinct()
packages.forEach { pkg ->
uris.forEach { uri ->
if (uri.scheme == ContentResolver.SCHEME_CONTENT && uri.authority == authority(context)) {
context.grantUriPermission(pkg, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
}
}
return packages.size
}
Three guards keep this narrow:
-
Only our own FileProvider URIs are granted. The check on
authoritymeans a URI from anywhere else is skipped, even if a bug passes one in. A unit test pins it. - Read only. No write grant, ever.
-
Package visibility is declared, not widened. On Android 11+,
queryIntentActivitiessees only the apps your manifest says you need. A<queries>entry forSENDandSEND_MULTIPLEwith*/*gives exactly the apps that can receive a share, without asking for a list of every installed package:
<queries>
<intent>
<action android:name="android.intent.action.SEND" />
<data android:mimeType="*/*" />
</intent>
<intent>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<data android:mimeType="*/*" />
</intent>
</queries>
The activity-level flag stays on the intent and on the chooser as well. The package grant is in addition, not instead.
The trade-off: every app that could receive the share can read that copy until it is deleted, not only the one the person picks. That is why the copies are short-lived (next section) and why only copies the person chose to share ever get a grant.
Fix 3: typed ClipData with every item
Some receivers read EXTRA_STREAM; others read ClipData only. For a multi-file share, a ClipData with one item and a generic type left those apps seeing one file, or a file of unknown type. Now the clip carries every URI and every distinct MIME type:
fun clipFor(label: String, uris: List<Uri>, mimes: List<String>): ClipData {
val types = mimes.filter { it.isNotBlank() }.distinct()
.ifEmpty { listOf(ClipDescription.MIMETYPE_UNKNOWN) }
return ClipData(ClipDescription(label, types.toTypedArray()), ClipData.Item(uris.first())).also { clip ->
uris.drop(1).forEach { clip.addItem(ClipData.Item(it)) }
}
}
The intent's own type is the narrowest type that covers the whole selection: the exact type when all items agree, the family (image/*) when only the family agrees, and */* otherwise or when any type is unknown.
Fix 4: delete the copies, and revoke as you delete
Copies in cache are still copies of someone's documents. They should not pile up. Files in the two share folders older than 3 days are deleted at app start and again at every share. Before each delete, the grant on that file's URI is revoked:
fun prune(cacheRoot: File, now: Long, keepMs: Long = KEEP_MS, beforeDelete: (File) -> Unit = {}): List<File> {
val cutoff = now - keepMs
val deleted = ArrayList<File>()
for (name in listOf("album_pdf", "share_out")) {
val dir = File(cacheRoot, name)
if (!dir.isDirectory) continue
dir.walkBottomUp().forEach { f ->
if (f == dir) return@forEach
if (f.isFile && f.lastModified() < cutoff) {
beforeDelete(f) // revokeUriPermission happens here
if (f.delete()) deleted += f
} else if (f.isDirectory && f.list().isNullOrEmpty()) {
f.delete()
}
}
}
return deleted
}
Why 3 days and not "after sending"? The app never knows when, or whether, the person pressed send in the other app. It only opens the share sheet; the person picks the app and presses send there. A short fixed window gives a slow upload or a "send it later" time to finish, and still keeps the cache small.
prune takes the cache root and the clock as parameters, so the tests run on a temp folder with fake times: only old files in our two folders go, a missing folder is a no-op, the callback runs before each delete (so revoking can't be skipped), and empty per-share folders are removed.
Takeaways
-
FLAG_GRANT_READ_URI_PERMISSIONon an intent belongs to the receiving activity. Apps that hand off from a share screen to another screen can lose it. - "Images work, documents don't" often means the receiver had its own route to the images, not that your document code is wrong.
- Never pass on a URI from someone else's grant. Copy into your own FileProvider, with the real name and type.
-
grantUriPermission(package, ...)outlives the screen. Limit it to your own authority, read only, and the packages a<queries>entry already lets you see. - Put every item and every type in
ClipData. - Copies you grant out need an expiry, and the revoke belongs in the same step as the delete.
QuickDial is on Google Play. It never sends anything on its own: the person picks the app and presses send there. Independent app, not affiliated with WhatsApp LLC or Meta.
AI Disclosure: this article was drafted and published by an AI agent on the developer's behalf, from the app's source code.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.