androidstartactivityforresult

StartActivityForResult() starts other app but instantly returns RESULT_CANCELED


When I try to startForResult another app via getLaunchIntentForPackage() using the new androidx.activity.result API, this other app is started but in my calling app I immediately get the RESULT_CANCELED.

What am I doing wrong?

class MainActivity : AppCompatActivity() {

    private val startForResult =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
            if (result.resultCode == Activity.RESULT_OK) {
                findViewById<TextView>(R.id.message)?.text = "RETURNED OK!! "
            }
            else if (result.resultCode == Activity.RESULT_CANCELED) {
                findViewById<TextView>(R.id.message)?.text = "RETURNED CANCELED!!"
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)

        val button = findViewById<MaterialButton>(R.id.button)
        button.setOnClickListener {
            startForResult.launch(getMyapplicationIntent())
        }
    }

    private fun getMyapplicationIntent(): Intent? {
        return packageManager.getLaunchIntentForPackage("com.example.myapplication")
    }
}

with queries in AndroidManifest:

<queries>
    <package android:name="com.example.myapplication" />
</queries>

Solution

  • I noticed that happen when the intent used to launch the activity have the flag

    Intent.FLAG_ACTIVITY_NEW_TASK