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
Certainly! To implement the
pickFolderfunction in yourMediaPlugin, you need to:- Request the necessary permissions (if not already granted).
- Launch an intent to let the user pick a folder (using
Intent.ACTION_OPEN_DOCUMENT_TREE). - Handle the result and return the selected folder's URI (or its contents) to the JS side.
Below is a complete implementation for the
pickFolderfunction, including permission handling and intent launching.
Note: This code assumes you are using the new Activity Result API (which is recommended).
class MediaPlugin(private val activity: Activity) : Plugin(activity) { private val TAG = "TauriMediaFolderPicker" private var lastInvoke: Invoke? = null // Launcher for folder picker private val folderPickerLauncher: ActivityResultLauncher<Intent> = activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> val invoke = lastInvoke lastInvoke = null if (result.resultCode == Activity.RESULT_OK) { val uri: Uri? = result.data?.data if (uri != null) { val jsObj = JSObject() jsObj.put("uri", uri.toString()) invoke?.resolve(jsObj) } else { invoke?.reject("No folder selected") } } else { invoke?.reject("Folder picking cancelled") } } @Command fun pickFolder(invoke: Invoke) { // Save the invoke to resolve/reject later lastInvoke = invoke // Check permissions val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { arrayOf(Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO) } else { arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE) } val missingPermissions = permissions.filter { ContextCompat.checkSelfPermission(activity, it) != PackageManager.PERMISSION_GRANTED } if (missingPermissions.isNotEmpty()) { ActivityCompat.requestPermissions(activity, missingPermissions.toTypedArray(), 1001) // You should handle the result in onRequestPermissionsResult and re-call pickFolder if granted invoke.reject("Permission required") return } // Launch folder picker val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) folderPickerLauncher.launch(intent) } }
Notes:
- Permissions:
- On Android 13+ (
TIRAMISU), you needREAD_MEDIA_IMAGESandREAD_MEDIA_VIDEO. - On older versions, you need
READ_EXTERNAL_STORAGE.
- On Android 13+ (
- Result Handling:
- The selected folder's URI is returned to JS as a string.
- Permissions Result:
- For a production app, you should handle
onRequestPermissionsResultand re-callpickFolderif permissions are granted. - For simplicity, this code just rejects if permissions are missing.
- For a production app, you should handle
If you want to handle permissions more robustly, you can use an
ActivityResultLauncherfor permissions as well, or handleonRequestPermissionsResultin your activity and call back into the plugin.Let me know if you need that part as well!
- User
why not use folderPickerLauncher as a function?
- Assistant
Great question!
Let’s clarify whyfolderPickerLauncheris typically a property, not a function.
1. What is
folderPickerLauncher?folderPickerLauncheris an instance ofActivityResultLauncher<Intent>.
It is not a function; it is an object that you use to launch an intent and receive a result asynchronously.You create it like this:
val folderPickerLauncher = activity.registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { result -> // handle result here }
2. Why not use it as a function?
-
Registration:
registerForActivityResultmust be called once (typically at initialization), and the returned launcher must be retained (as a property/field).
If you call it as a function every time, you would be registering a new launcher each time, which is not how the API is designed to be used. -
Lifecycle Awareness:
The launcher is lifecycle-aware. It is tied to the activity or fragment’s lifecycle.
Registering it once and keeping it as a property ensures it is properly managed and avoids memory leaks or unexpected behavior. -
Usage:
When you want to launch the picker, you call:folderPickerLauncher.launch(intent)If it were a function, you’d have to re-register every time, which is unnecessary and potentially problematic.
3. What if you made it a function?
If you did:
fun folderPickerLauncher() = activity.registerForActivityResult(...)- You’d be registering a new launcher every time you call the function.
- Only the most recently registered launcher would receive the result.
- You could leak memory or miss results, and it would be hard to manage the callback.
4. Best Practice
- Register once (as a property, usually in the class body or
onCreate). - Launch as needed by calling
.launch(intent).
Summary Table
Approach Pros Cons Property (recommended) Correct lifecycle, safe None Function (re-register) None Leaks, missed results, not lifecycle-aware, not intended
In short:
folderPickerLauncheris a launcher object, not a function.
Register it once, keep it as a property, and use it to launch intents as needed.
If you want a code example of both approaches, let me know!
-
- User
Do we need ActivityCallback or PermissionCallback annotations?
- Assistant
Short answer:
No, you do not needActivityCallbackorPermissionCallbackannotations when using the Activity Result API (registerForActivityResult) as shown in your code.
Those annotations are typically used in older Tauri Android plugin patterns or when you want Tauri to automatically route activity/permission results to your plugin methods.
When are these annotations needed?
1.
ActivityCallback- Used when you want your plugin to receive results from activities started with
startActivityForResult. - With the new Activity Result API (
registerForActivityResult), you handle results via the lambda you provide, so you don’t need this annotation.
2.
PermissionCallback- Used when you want your plugin to receive results from permission requests (i.e.,
onRequestPermissionsResult). - If you use the Activity Result API for permissions (
ActivityResultContracts.RequestPermissionorRequestMultiplePermissions), you handle the result in the lambda, so you don’t need this annotation.
When would you use them?
- If you are using legacy Android APIs (
startActivityForResult,requestPermissions) and want Tauri to route the result to a specific method in your plugin, you would use these annotations. - Example:
@ActivityCallback fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { ... } @PermissionCallback fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { ... }
In your code:
You are using:
val folderPickerLauncher = activity.registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { result -> ... }This is the modern, recommended way.
No annotation is needed.
Summary Table
Use case Annotation needed? Modern API alternative? Handle activity result (legacy) Yes ( @ActivityCallback)Use registerForActivityResultinsteadHandle permission result (legacy) Yes ( @PermissionCallback)Use registerForActivityResultinsteadUsing Activity Result API No N/A
Conclusion:
If you use the Activity Result API (
registerForActivityResult), you do not needActivityCallbackorPermissionCallbackannotations.If you want an example of handling permissions with the modern API, just ask!
- Used when you want your plugin to receive results from activities started with
- User
How do I do it without registerForActivityResult?
- Assistant
Great question!
If you don’t useregisterForActivityResult(the modern API), you must use the legacy Android APIs:startActivityForResultfor launching activities for a resultonActivityResultfor receiving the resultrequestPermissionsfor requesting permissionsonRequestPermissionsResultfor receiving permission results
In a Tauri plugin, you can use the
@ActivityCallbackand@PermissionCallbackannotations to have Tauri route these results to your plugin methods.
Example: Folder Picker Without
registerForActivityResult1. Launch the Folder Picker
@Command fun pickFolder(invoke: Invoke) { lastInvoke = invoke // Check permissions (as before) val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { arrayOf(Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO) } else { arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE) } val missingPermissions = permissions.filter { ContextCompat.checkSelfPermission(activity, it) != PackageManager.PERMISSION_GRANTED } if (missingPermissions.isNotEmpty()) { ActivityCompat.requestPermissions(activity, missingPermissions.toTypedArray(), 1001) // The result will be handled in onRequestPermissionsResult return } // Launch folder picker val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) activity.startActivityForResult(intent, 2001) }
2. Handle the Activity Result
@ActivityCallback fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == 2001) { val invoke = lastInvoke lastInvoke = null if (resultCode == Activity.RESULT_OK) { val uri: Uri? = data?.data if (uri != null) { val jsObj = JSObject() jsObj.put("uri", uri.toString()) invoke?.resolve(jsObj) } else { invoke?.reject("No folder selected") } } else { invoke?.reject("Folder picking cancelled") } } }
3. Handle Permission Result
@PermissionCallback fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == 1001) { if (grantResults.all { it == PackageManager.PERMISSION_GRANTED }) { // Permissions granted, re-launch the folder picker pickFolder(lastInvoke!!) } else { lastInvoke?.reject("Permission required") lastInvoke = null } } }
Summary Table
Task Modern API ( registerForActivityResult)Legacy API (with Tauri Annotations) Launch activity for result launcher.launch(intent)activity.startActivityForResult(intent, code)Receive result Lambda in registration @ActivityCallbackmethodRequest permissions launcher.launch(permissions)ActivityCompat.requestPermissions(...)Receive permission result Lambda in registration @PermissionCallbackmethod
Conclusion
- Without
registerForActivityResult, usestartActivityForResultandrequestPermissions. - Use
@ActivityCallbackand@PermissionCallbackin your Tauri plugin to handle results.
Let me know if you want a full, copy-paste-ready example!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.