Skip to content

Instantly share code, notes, and snippets.

@DenisShov
Created July 25, 2022 12:12
Show Gist options
  • Save DenisShov/c5f4297540ad5c3842a9b649d260d166 to your computer and use it in GitHub Desktop.
Save DenisShov/c5f4297540ad5c3842a9b649d260d166 to your computer and use it in GitHub Desktop.
Open a file from Downloads folder using FileProvider
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/rc_file_path" />
</provider>
private fun openFile(file: File?) {
val intent = Intent(Intent.ACTION_VIEW)
val data: Uri
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
data = Uri.fromFile(file)
} else {
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
data = FileProvider.getUriForFile(this, "$packageName.provider", file)
}
intent.setDataAndType(data, getMimeType(data))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
private fun getMimeType(uri: Uri): String? {
val mimeType: String? = if (ContentResolver.SCHEME_CONTENT == uri.scheme) {
val cr = contentResolver
cr.getType(uri)
} else {
val fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString())
MimeTypeMap.getSingleton().getMimeTypeFromExtension(
fileExtension.lowercase(Locale.getDefault())
)
}
return mimeType
}
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="rc_external_path" path="."/>
</paths>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment