Search code examples
androidtextandroid-intentaction-send

Is there a way to share plain text to another app without the user having to choose that other app


I am trying to allow my app to share some plain text to another app called 'macrodroid'. As the destination app is always the same I don't want my users to have to manually select the app every single time so I want to know if it is possible to send the text without the user having to choose. I couldn't find a solution for this myself and when searching online they all seem to require user input.

This is what I have so far, but as I said this forces the user to choose an app

val sintent = Intent(Intent.ACTION_SEND)
sintent.putExtra(Intent.EXTRA_TEXT, "variable to share text to macrodroid here")
sintent.setType("text/plain")
startActivity(sintent)

Solution

  • use the below function.

    fun shareTextToApp(context: Context, text: String, packageName: String) {
        // Create the intent
        val intent = Intent(Intent.ACTION_SEND)
        intent.type = "text/plain"
        intent.putExtra(Intent.EXTRA_TEXT, text)
    
        // Set the target app's package name
        intent.setPackage(packageName)
    
        // Verify that the app is installed and can handle the intent
        if (intent.resolveActivity(context.packageManager) != null) {
            context.startActivity(intent)
        } else {
            Toast.makeText(context, "App not installed", Toast.LENGTH_SHORT).show()
        }
    }