Created
July 25, 2022 12:12
-
-
Save DenisShov/c5f4297540ad5c3842a9b649d260d166 to your computer and use it in GitHub Desktop.
Open a file from Downloads folder using FileProvider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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