Understanding URIs in Android

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

  • Always use Uri.parse() or appropriate builder methods
  • Handle URI permissions carefully
  • Use ContentResolver for content URIs
  • Be mindful of the storage access framework and scoped storage


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.

要查看或添加评论,请登录

Abdelrhman Ghanem的更多文章

  • Content Providers in Android

    Content Providers in Android

    What Is a Content Provider? A Content Provider acts as an interface for applications to access and modify data from…

  • WorkManager in Android

    WorkManager in Android

    What is WorkManager? WorkManager is an API Android Jetpack provides for scheduling deferrable, asynchronous tasks that…

  • Foreground Services in Android

    Foreground Services in Android

    A Foreground Service is an Android service that performs a task while actively notifying the user, generally through a…

  • Broadcasts and Broadcast Receivers in Android

    Broadcasts and Broadcast Receivers in Android

    Broadcasts in Android allow applications and the Android system to send messages across apps and system components…

  • Intents and Intent Filters in Android

    Intents and Intent Filters in Android

    What is an Intent? An in Android is a messaging object used to request actions from other components like activities…

  • Android Resources and Qualifiers

    Android Resources and Qualifiers

    When building an Android app, you want it to look and work well across all devices. To do that, Android gives us…

  • Context in Android

    Context in Android

    What is Context? In Android, represents the current state of the application. It provides access to various resources…

  • Understanding Configuration Changes and ViewModel in Android

    Understanding Configuration Changes and ViewModel in Android

    1. What Are Configuration Changes? Configuration changes occur when the device environment changes in a way that…

  • Android Back Stack, Tasks, and Launch Modes

    Android Back Stack, Tasks, and Launch Modes

    In Android, managing screen navigation and app flows effectively depends on understanding the backstack, tasks, and…

  • Android Activity & Fragment Lifecycle

    Android Activity & Fragment Lifecycle

    In Android development, Activities and Fragments are essential components that help create engaging user interfaces…

社区洞察

其他会员也浏览了