我在 ActivityA 上,尝试使用字符串输入启动 ActivityB,进行一些工作,然后将字符串输出返回给 ActivityA。我根据本教程和ActivityResultContract
(都在下面列出)创建了 Activity Result API 帮助程序类。我在 ActivityA 的 onCreate() 方法中注册活动结果:
private lateinit var linkLauncher: ActivityResultHandler<String, String?>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
linkLauncher = ActivityResultHandler(this, extWebLinkAction, GetExtWebLinkContract())
}
问题是当我调用linkLauncher.execute()
方法时,该方法又调用ActivityResultLauncher
'slaunch() 方法,这两个合约方法都在 ActivityB 启动之前被调用。
这是我尝试将结果从 ActivityB 返回到 ActiviteA 的方式:
setResult(Activity.RESULT_OK, Intent().apply {
putExtra(LINK_TRANSPORT_EXTRA, link)
})
提到的类的列表。
助手类:
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.ActivityResultRegistry
import androidx.activity.result.contract.ActivityResultContract
import androidx.lifecycle.LifecycleOwner
import java.util.*
interface IActivityResult<I> {
fun execute(input: I)
}
class ActivityResultHandler<I, O>(
private val activity: ComponentActivity,
private val func: (O) -> Unit,
private val contract: ActivityResultContract<I, O>
) : IActivityResult<I> by ActivityResultHandlerImpl(
activity.activityResultRegistry,
activity,
func,
contract
) {
private class ActivityResultHandlerImpl<I, O>(
private val registry: ActivityResultRegistry,
private val lifecycleOwner: LifecycleOwner,
private val func: (O) -> Unit,
private val contract: ActivityResultContract<I, O>
): IActivityResult<I> {
private val callback = ActivityResultCallback<O> { output ->
func(output)
}
private var resultLauncher: ActivityResultLauncher<I>
= registry.register(UUID.randomUUID().toString(), lifecycleOwner, contract, callback)
override fun execute(input: I) {
resultLauncher.launch(input)
}
}
}
这是我的ActivityResultContract
:
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.activity.result.contract.ActivityResultContract
import com.zultys.mobiledroid.mvvm.ui.chat.group.GroupActivity
import com.zultys.mobiledroid.mvvm.ui.profile.extweb.ExtWebLinkFragment
import com.zultys.mobiledroid.utils.extensions.logd
class GetLinkContract: ActivityResultContract<String, String?>() {
override fun createIntent(context: Context, input: String): Intent =
context.intentFor<ActivityB>
.newTask()
.putExtra(GROUP_ID_EXTRA, groupId)
override fun parseResult(resultCode: Int, intent: Intent?): String? =
when {
resultCode != Activity.RESULT_OK -> null
else -> intent?.getStringExtra(LINK_TRANSPORT_EXTRA)
}
}