Skip to content

Instantly share code, notes, and snippets.

@root-ansh
Created September 7, 2025 10:51
Show Gist options
  • Select an option

  • Save root-ansh/1fd4b1a7e3f863d726be24eca463da2a to your computer and use it in GitHub Desktop.

Select an option

Save root-ansh/1fd4b1a7e3f863d726be24eca463da2a to your computer and use it in GitHub Desktop.
fun Context.openSystemViewerForSAFUri(uri: Uri?) {
uri?:return
val mimeType1 = FileInfo.fromSAFUri(this,uri)?.mimeType
val extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString())
val mimeType2 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.lowercase())
val mimeType3 = "*/*"
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, mimeType1?:mimeType2?:mimeType3)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this, "No app found to open this file type", Toast.LENGTH_SHORT).show()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment