import android.Manifest import android.app.Activity import android.content.ContentUris…
- User
import android.Manifest import android.app.Activity import android.content.ContentUris import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.provider.MediaStore import android.util.Log import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import app.tauri.annotation.Command import app.tauri.annotation.InvokeArg import app.tauri.annotation.Permission // <--- ADD THIS IMPORT import app.tauri.annotation.TauriPlugin import app.tauri.plugin.Invoke // For interacting with Rust commands import app.tauri.plugin.JSObject // For returning data to JS import app.tauri.plugin.Plugin import app.tauri.plugin.PluginHandle import com.google.gson.Gson
import org.json.JSONArray import org.json.JSONObject
@TauriPlugin( permissions = [ Permission(strings = [Manifest.permission.READ_EXTERNAL_STORAGE], alias = "readStorage"), Permission(strings = [Manifest.permission.READ_MEDIA_IMAGES], alias = "readMediaImages"), Permission(strings = [Manifest.permission.READ_MEDIA_VIDEO], alias = "readMediaVideo") ] ) class MediaPlugin(private val activity: Activity) : Plugin(activity) {
private val TAG = "TauriMediaFolderPicker" private var lastInvoke: Invoke? = null @InvokeArg class MediaItem( val id: String, val displayName: String?, val path: String, val mimeType: String?, val dateAdded: Long, val width: Int, val height: Int, val duration: Long? = null ) /** * This method is exposed to the Rust backend and will be called when the frontend * invokes the corresponding Rust command. */ @Command fun pickFolder(invoke: Invoke) { // Fill in this function } Assistant
You're working on a Tauri Android plugin and want to implement a method (
pickFolder) that opens an intent to let the user pick a folder (directory) and then returns media items from that folder.Below is a complete implementation of the
pickFolderfunction, along with supporting code for handling permissions, launching the folder picker, and retrieving media files (images and videos) from the selected folder.
✅ Updated
MediaPlugin.kt– Complete Implementationimport android.Manifest import android.app.Activity import android.content.ContentUris import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.provider.MediaStore import android.util.Log import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import app.tauri.annotation.Command import app.tauri.annotation.InvokeArg import app.tauri.annotation.Permission import app.tauri.annotation.TauriPlugin import app.tauri.plugin.Invoke import app.tauri.plugin.JSObject import app.tauri.plugin.Plugin import app.tauri.plugin.PluginHandle import com.google.gson.Gson import org.json.JSONArray import org.json.JSONObject @TauriPlugin( permissions = [ Permission(strings = [Manifest.permission.READ_EXTERNAL_STORAGE], alias = "readStorage"), Permission(strings = [Manifest.permission.READ_MEDIA_IMAGES], alias = "readMediaImages"), Permission(strings = [Manifest.permission.READ_MEDIA_VIDEO], alias = "readMediaVideo") ] ) class MediaPlugin(private val activity: Activity) : Plugin(activity) { private val TAG = "TauriMediaFolderPicker" private var lastInvoke: Invoke? = null private var folderPickerLauncher: ActivityResultLauncher<Intent>? = null @InvokeArg class MediaItem( val id: String, val displayName: String?, val path: String, val mimeType: String?, val dateAdded: Long, val width: Int, val height: Int, val duration: Long? = null ) override fun onCreate(handle: PluginHandle) { super.onCreate(handle) // Register activity result launcher for folder picker folderPickerLauncher = activity.registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { result -> if (result.resultCode == Activity.RESULT_OK) { val data: Intent? = result.data val uri: Uri? = data?.data uri?.let { folderUri -> val mediaItems = getMediaFromFolder(folderUri) val response = JSObject() response.put("folder", folderUri.toString()) response.put("media", Gson().toJson(mediaItems)) lastInvoke?.resolve(response) } ?: run { lastInvoke?.reject("No folder selected.") } } else { lastInvoke?.reject("Folder selection canceled.") } } } @Command fun pickFolder(invoke: Invoke) { this.lastInvoke = invoke // Check runtime permissions if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_MEDIA_VIDEO) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( activity, arrayOf( Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO ), 100 ) return } } else { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( activity, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 100 ) return } } // Launch folder picker val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply { flags = Intent.FLAG_GRANT_READ_URI_PERMISSION } folderPickerLauncher?.launch(intent) } private fun getMediaFromFolder(folderUri: Uri): List<MediaItem> { val mediaItems = mutableListOf<MediaItem>() // Query images val imageProjection = arrayOf( MediaStore.MediaColumns._ID, MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.MIME_TYPE, MediaStore.MediaColumns.DATE_ADDED, MediaStore.Images.ImageColumns.WIDTH, MediaStore.Images.ImageColumns.HEIGHT ) val imageCursor = activity.contentResolver.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageProjection, null, null, null ) imageCursor?.use { val idColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns._ID) val displayNameColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME) val pathColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA) val mimeTypeColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns.MIME_TYPE) val dateAddedColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns.DATE_ADDED) val widthColumn = it.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.WIDTH) val heightColumn = it.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.HEIGHT) while (it.moveToNext()) { val id = it.getLong(idColumn) val displayName = it.getString(displayNameColumn) val path = it.getString(pathColumn) val mimeType = it.getString(mimeTypeColumn) val dateAdded = it.getLong(dateAddedColumn) val width = it.getInt(widthColumn) val height = it.getInt(heightColumn) val contentUri = ContentUris.withAppendedId( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id ) if (path?.startsWith(folderUri.path.orEmpty()) == true) { mediaItems.add( MediaItem( id = contentUri.toString(), displayName = displayName, path = path, mimeType = mimeType, dateAdded = dateAdded, width = width, height = height ) ) } } } // Query videos val videoProjection = arrayOf( MediaStore.MediaColumns._ID, MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.MIME_TYPE, MediaStore.MediaColumns.DATE_ADDED, MediaStore.Video.VideoColumns.WIDTH, MediaStore.Video.VideoColumns.HEIGHT, MediaStore.Video.VideoColumns.DURATION ) val videoCursor = activity.contentResolver.query( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoProjection, null, null, null ) videoCursor?.use { val idColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns._ID) val displayNameColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME) val pathColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA) val mimeTypeColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns.MIME_TYPE) val dateAddedColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns.DATE_ADDED) val widthColumn = it.getColumnIndexOrThrow(MediaStore.Video.VideoColumns.WIDTH) val heightColumn = it.getColumnIndexOrThrow(MediaStore.Video.VideoColumns.HEIGHT) val durationColumn = it.getColumnIndexOrThrow(MediaStore.Video.VideoColumns.DURATION) while (it.moveToNext()) { val id = it.getLong(idColumn) val displayName = it.getString(displayNameColumn) val path = it.getString(pathColumn) val mimeType = it.getString(mimeTypeColumn) val dateAdded = it.getLong(dateAddedColumn) val width = it.getInt(widthColumn) val height = it.getInt(heightColumn) val duration = it.getLong(durationColumn) val contentUri = ContentUris.withAppendedId( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id ) if (path?.startsWith(folderUri.path.orEmpty()) == true) { mediaItems.add( MediaItem( id = contentUri.toString(), displayName = displayName, path = path, mimeType = mimeType, dateAdded = dateAdded, width = width, height = height, duration = duration ) ) } } } return mediaItems } }
🧠 Notes:
- Folder Picker: Uses
Intent.ACTION_OPEN_DOCUMENT_TREEto allow users to select a directory. - Permissions:
- For Android 13+,
READ_MEDIA_IMAGESandREAD_MEDIA_VIDEOare used. - For older versions, fallback to
READ_EXTERNAL_STORAGE.
- For Android 13+,
- Media Retrieval:
- Queries both
MediaStore.Images.MediaandMediaStore.Video.Media. - Filters results based on whether the file path starts with the selected folder’s path.
- Queries both
🚀 Usage in Rust (Tauri backend):
Make sure you expose this command in your Rust plugin:
#[tauri::command] async fn pick_folder<R: Runtime>(app: AppHandle<R>, window: Window<R>) -> Result<String, String> { let plugin = app.get_plugin::<MediaPlugin>("media").map_err(|e| e.to_string())?; let response = plugin.invoke("pickFolder", None).await.map_err(|e| e.to_string())?; Ok(response) }And register the command in your plugin setup.
Let me know if you need help wiring this up with Tauri's frontend or Rust side!
- Folder Picker: Uses
- User
why not use folderPickerLauncher as a function?
Assistant
Great question! 🎯
You're asking why we assign
folderPickerLauncheras a property of the class (MediaPlugin) rather than defining it as a function. Let's explore both approaches and understand the trade-offs.
✅ TL;DR – Why not use
folderPickerLauncheras a function?Because
ActivityResultLauncher<Intent>must be registered early in the lifecycle (typically inonCreate, or during plugin initialization), and needs to persist across method calls — which makes it unsuitable for being a local variable inside a function likepickFolder.Also, Tauri plugins are often stateful and need to hold references to things like launchers, callbacks, etc., so storing them as properties is appropriate.
🔍 In Detail:
1. ActivityResultLauncher Needs Lifecycle Awareness
The launcher returned by:
activity.registerForActivityResult(...)is tied to the
Activity's lifecycle. If you try to create this inside a short-lived function likepickFolder(), and then re-create it every time, you might run into issues like:- Launchers not receiving results correctly.
- Memory leaks or inconsistent behavior if not handled carefully.
By assigning it to a property (
folderPickerLauncher), we ensure that it's created once and reused safely.2. Avoid Re-registering Every Time
Every call to
registerForActivityResult()registers a new contract with the system. You only want to do this once, not every timepickFolder()is called.This means:
override fun onCreate(handle: PluginHandle) { folderPickerLauncher = activity.registerForActivityResult(...) }is the right place for this kind of setup.
3. Cleaner Separation of Concerns
By registering the launcher in
onCreate()and using it inpickFolder(), we separate:- Initialization logic (setting up result handlers)
- Trigger logic (launching the intent)
This makes code more readable and maintainable.
❌ What Happens If You Try to Make It a Function?
Let’s imagine something like:
fun getFolderPickerLauncher(): ActivityResultLauncher<Intent> { return activity.registerForActivityResult(...) { ... } }Then calling:
@Command fun pickFolder(invoke: Invoke) { val launcher = getFolderPickerLauncher() launcher.launch(Intent(...)) }This would cause:
- A new launcher to be created every time
pickFolder()is called. - The callback would be redefined each time — possibly leading to memory leaks or unexpected behavior.
- Android may throw errors or ignore repeated registrations.
✅ Best Practice Summary
Goal Recommended Approach Register an activity result handler Use onCreateor init blockStore the launcher As a class property Trigger the intent In your command method ( pickFolder)
💡 Bonus Tip: What if I want multiple launchers?
If your plugin supports multiple operations (e.g., folder picker, file picker, camera, etc.), register each one once and store them all as properties:
private var folderLauncher: ActivityResultLauncher<Intent>? = null private var fileLauncher: ActivityResultLauncher<Intent>? = null private var cameraLauncher: ActivityResultLauncher<Intent>? = nullEach gets initialized once, used many times.
✅ Final Thoughts
So, to answer your question directly:
Why not use
folderPickerLauncheras a function?Because:
- It should be registered once and reused.
- It needs to survive beyond a single function call.
- It's lifecycle-aware and shouldn't be recreated on every command invocation.
Keeping it as a plugin class property ensures robustness, performance, and correctness.
Let me know if you'd like to see how to handle permissions or media scanning differently too!
- User
Do we need ActivityCallback or PermissionCallback annotations?
Assistant
Great question! 👍
You're asking whether you need to use
@ActivityCallbackor@PermissionCallbackannotations in your Tauri Android plugin — and that’s a solid point to consider when dealing with Android'sActivityResultLauncher, permissions, and lifecycle events.
✅ Short Answer:
❗ You do not need the
@ActivityCallbackor@PermissionCallbackannotations if:- You're using
ActivityResultLauncher(like withregisterForActivityResult) - You're handling permission results via standard Android APIs (
onRequestPermissionsResult, etc.)
These annotations are specific to Tauri 1.x and early versions of Tauri 2, where plugins needed to manually register callbacks via reflection. However, in modern Tauri 2+ Android plugin architecture, these annotations are not required and are mostly obsolete.
🧠 Long Answer: What Were They For?
1.
@ActivityCallbackUsed to annotate methods that should be called when the app receives an activity result (e.g., from
startActivityForResult). In older versions of Tauri, this was how you hooked into Android'sonActivityResult.Example (old style):
@ActivityCallback("folderPicker") fun onFolderPicker(requestCode: Int, resultCode: Int, data: Intent?) { // Handle folder pick }But now, since you're using:
activity.registerForActivityResult(...)You don't need this annotation anymore. That method handles everything directly with a lambda callback.
2.
@PermissionCallbackThis was used to route permission request results back to your plugin. It allowed Tauri to map permission request codes back to your plugin method.
Old example:
@PermissionCallback("storagePermission") fun handlePermissionResponse() { // Handle permission grant/deny }Nowadays, you can just check the permission result in:
override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray )inside your
Activity, and forward it to your plugin if needed.
🔁 So What Should You Do Now?
You're already doing it right ✅:
- Using
ActivityResultLauncherfor picking folders. - Handling permissions with
ActivityCompat.requestPermissions()andonRequestPermissionsResult().
No need to add those annotations unless you're maintaining compatibility with very old Tauri Android plugin patterns.
🛠️ If You Want to Handle Permissions From Activity
Here’s how you might forward permission results to your plugin:
In your
MainActivity.kt:class MainActivity : TauriActivity() { private var mediaPlugin: MediaPlugin? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mediaPlugin = pluginManager.getPlugin("media") as? MediaPlugin } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == 100) { // Same request code used in plugin mediaPlugin?.onPermissionsResult(permissions, grantResults) } } }Then in your
MediaPlugin.kt:Add a method:
fun onPermissionsResult(permissions: Array<String>, grantResults: IntArray) { val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED } if (allGranted) { // Re-launch folder picker or continue flow } else { lastInvoke?.reject("Permissions denied.") } }This gives you full control without needing
@PermissionCallback.
✅ Summary
Feature Needed Anymore? Why / Why Not @ActivityCallback❌ No Use ActivityResultLauncherinstead@PermissionCallback❌ No Use onRequestPermissionsResultdirectly
Let me know if you want help wiring up a cleaner way to handle permissions or results from your plugin!
- You're using
- User
How do I do it without registerForActivityResult?
Assistant
Great question! 🚀
You're asking:
How do I use folder picking on Android without
registerForActivityResult?This is relevant if you're working in an environment where
registerForActivityResultisn't available (e.g., older Tauri versions, custom wrappers, or specific compatibility constraints).
🔁 TL;DR – Short Answer
You can fall back to using the legacy approach:
startActivityForResult(Intent, requestCode)and handle the result manually in your
Activity'sonActivityResult()method.
✅ Step-by-Step Guide Without
registerForActivityResult1. Trigger Folder Picker from Plugin
In your plugin (
MediaPlugin.kt), launch the intent usingstartActivityForResult:@Command fun pickFolder(invoke: Invoke) { this.lastInvoke = invoke // Request permissions if needed (same as before) val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply { flags = Intent.FLAG_GRANT_READ_URI_PERMISSION } // Use startActivityForResult activity.startActivityForResult(intent, REQUEST_CODE_PICK_FOLDER) }Define the constant at the top of your class:
companion object { private const val REQUEST_CODE_PICK_FOLDER = 1234 }
2. **Handle Result in Your Activity
Since you’re not using
ActivityResultLauncher, you must overrideonActivityResultin your main activity:➤
MainActivity.ktclass MainActivity : TauriActivity() { private var mediaPlugin: MediaPlugin? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mediaPlugin = pluginManager.getPlugin("media") as? MediaPlugin } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CODE_PICK_FOLDER && resultCode == Activity.RESULT_OK) { val uri = data?.data mediaPlugin?.handleFolderSelection(uri) } else { mediaPlugin?.handleFolderSelection(null) } } }Don’t forget to define the same request code in your
MainActivity:companion object { const val REQUEST_CODE_PICK_FOLDER = 1234 }
3. **Add Handler Method in Plugin
In your
MediaPlugin.kt, add a function to process the result:fun handleFolderSelection(uri: Uri?) { if (uri == null) { lastInvoke?.reject("No folder selected.") return } val mediaItems = getMediaFromFolder(uri) val response = JSObject() response.put("folder", uri.toString()) response.put("media", Gson().toJson(mediaItems)) lastInvoke?.resolve(response) }
🧠 Notes
Feature Legacy Approach Start intent activity.startActivityForResult(...)Handle result Override onActivityResult()inActivityForward result Manually call plugin method like plugin.handleFolderSelection(uri)
⚠️ Caveats / Considerations
- ❗
startActivityForResultandonActivityResultare deprecated since AndroidX Activity 1.2.0, but still work. - 🧼 Cleaner for small apps/plugins, but harder to scale with many intents.
- 🔄 If possible, prefer
ActivityResultLauncherfor better lifecycle handling and cleaner architecture.
✅ When Should You Avoid
registerForActivityResult?Use the legacy pattern when:
- You're targeting very old Android versions (< API 21).
- You're working within a framework or wrapper that doesn't expose
ActivityResultRegistry. - You're debugging or migrating old plugins.
💡 Bonus Tip – Multiple Plugins Using
onActivityResultIf multiple plugins need to respond to different results, consider managing request codes carefully or creating a central dispatcher in your
MainActivity.
Let me know if you want this wrapped into a reusable base plugin or helper utility!
- ❗
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.