Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-2025-04-14· OpenAIHugging Face LMArena Human Preference 140K

import android.Manifest import android.app.Activity import android.content.ContentUris…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwen3-235b-a22b-no-thinking’s answer.
  1. 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
    }
    
  2. Assistant

    Certainly! To implement the pickFolder function in your MediaPlugin, you need to:

    1. Request the necessary permissions (if not already granted).
    2. Launch an intent to let the user pick a folder (using Intent.ACTION_OPEN_DOCUMENT_TREE).
    3. Handle the result and return the selected folder's URI (or its contents) to the JS side.

    Below is a complete implementation for the pickFolder function, 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 need READ_MEDIA_IMAGES and READ_MEDIA_VIDEO.
      • On older versions, you need READ_EXTERNAL_STORAGE.
    • Result Handling:
      • The selected folder's URI is returned to JS as a string.
    • Permissions Result:
      • For a production app, you should handle onRequestPermissionsResult and re-call pickFolder if permissions are granted.
      • For simplicity, this code just rejects if permissions are missing.

    If you want to handle permissions more robustly, you can use an ActivityResultLauncher for permissions as well, or handle onRequestPermissionsResult in your activity and call back into the plugin.

    Let me know if you need that part as well!

  3. User

    why not use folderPickerLauncher as a function?

  4. Assistant

    Great question!
    Let’s clarify why folderPickerLauncher is typically a property, not a function.


    1. What is folderPickerLauncher?

    folderPickerLauncher is an instance of ActivityResultLauncher<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:
      registerForActivityResult must 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

    ApproachProsCons
    Property (recommended)Correct lifecycle, safeNone
    Function (re-register)NoneLeaks, missed results, not lifecycle-aware, not intended

    In short:

    folderPickerLauncher is 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!

  5. User

    Do we need ActivityCallback or PermissionCallback annotations?

  6. Assistant

    Short answer:
    No, you do not need ActivityCallback or PermissionCallback annotations 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.RequestPermission or RequestMultiplePermissions), 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 caseAnnotation needed?Modern API alternative?
    Handle activity result (legacy)Yes (@ActivityCallback)Use registerForActivityResult instead
    Handle permission result (legacy)Yes (@PermissionCallback)Use registerForActivityResult instead
    Using Activity Result APINoN/A

    Conclusion:

    If you use the Activity Result API (registerForActivityResult), you do not need ActivityCallback or PermissionCallback annotations.

    If you want an example of handling permissions with the modern API, just ask!

  7. User

    How do I do it without registerForActivityResult?

  8. Assistant

    Great question!
    If you don’t use registerForActivityResult (the modern API), you must use the legacy Android APIs:

    • startActivityForResult for launching activities for a result
    • onActivityResult for receiving the result
    • requestPermissions for requesting permissions
    • onRequestPermissionsResult for receiving permission results

    In a Tauri plugin, you can use the @ActivityCallback and @PermissionCallback annotations to have Tauri route these results to your plugin methods.


    Example: Folder Picker Without registerForActivityResult

    1. 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

    TaskModern API (registerForActivityResult)Legacy API (with Tauri Annotations)
    Launch activity for resultlauncher.launch(intent)activity.startActivityForResult(intent, code)
    Receive resultLambda in registration@ActivityCallback method
    Request permissionslauncher.launch(permissions)ActivityCompat.requestPermissions(...)
    Receive permission resultLambda in registration@PermissionCallback method

    Conclusion

    • Without registerForActivityResult, use startActivityForResult and requestPermissions.
    • Use @ActivityCallback and @PermissionCallback in your Tauri plugin to handle results.

    Let me know if you want a full, copy-paste-ready example!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.