Understanding URIs in Android
A Uniform Resource Identifier (URI) is a string of characters uniquely identifying a resource. In Android, URIs are crucial for accessing and managing different types of resources across the system.
URI Types in Android
1. Resource URI => (android.resource://)
Used to reference application resources like drawables, layouts, or raw files.
// Accessing a drawable resource
val resourceUri = Uri.parse("android.resource://${context.packageName}/${R.drawable.my_image}")
Use Case: Referencing internal app resources, loading images, or accessing raw files bundled with the app.
2. File URI (file://)
Points to a file on the device's local storage.
Accessing files stored on external storage (e.g., SD card) may require permission, especially on Android 10 (API level 29) and above due to scoped storage restrictions.
// Creating a file URI
val file = File(filesDir, "example.txt")
val fileUri = Uri.fromFile(file)
// Sharing a file
val shareIntent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_STREAM, fileUri)
}
startActivity(Intent.createChooser(shareIntent, "Share File"))
Use Case: Sharing files, accessing local storage, working with downloaded or created files.
领英推荐
3. Content URI (content://)
Used to access data managed by content providers, typically for media, contacts, or app-specific databases.
val galleryLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { galleryUri ->
try {
// TODO SOMETHING 'galleryUri'
} catch (e: Exception) {
e.printStackTrace()
}
})
Use Case: Accessing system media, contacts, or other content provider-managed data.
4. Data URI (data:)
Embeds data directly in the URI, typically used for small pieces of data or inline content.
// Creating a data URI for a simple text
val dataUri = Uri.parse("data:text/plain;base64,SGVsbG8gV29ybGQ=")
// Using with WebView
webView.loadUrl(dataUri.toString())
// Base64 encoded image
val base64Image = "data:image/png;base64,iVBORw0KGgoAAAANSUh..."
val imageUri = Uri.parse(base64Image)
Use Case: Embedding small data directly in URLs, loading inline content in WebViews.
Actually I don't use it a lot and prefer to save the file in res and use Resource URI
Best Practices
Conclusion:
Understanding URIs in Android is fundamental for building robust and efficient applications. By mastering the various URI types and best practices outlined in this guide, developers can enhance the functionality, security, and performance of their Android apps. As you continue your journey in Android development, don’t hesitate to explore further and experiment with URIs to unlock new possibilities and functionalities within your applications.