5

是否有任何默认方式来获取请求代码ActivityResultContract

我知道StartActivityForResult合同,它返回ActivityResult,但没有requestCode,只有resultCode

我可以做这样的事情,但也许有更好的解决方案:

class StartActivityForResult : ActivityResultContract<ActivityInput, ActivityOutput?>() {
    override fun createIntent(
        context: Context,
        input: ActivityInput
    ): Intent {
        return input.data.apply { putExtra(requestCodeKey, input.requestCode) }
    }

    override fun parseResult(resultCode: Int, intent: Intent?): ActivityOutput? {
        return if (intent == null || resultCode != Activity.RESULT_OK) null
        else ActivityOutput(
            // should never return default value
            requestCode = intent.getIntExtra(requestCodeKey, -1),
            resultCode = resultCode,
            data = intent
        )
    }

    override fun getSynchronousResult(
        context: Context,
        input: ActivityInput?
    ): SynchronousResult<ActivityOutput?>? {
        return if (input == null) SynchronousResult(null) else null
    }

    companion object {
        const val requestCodeKey = "requestCodeKey";
    }
}
data class ActivityInput(val requestCode: Int, val data: Intent)
data class ActivityOutput(val requestCode: Int,
                          val resultCode: Int,
                          val data: Intent
)
4

0 回答 0