我正在 Kotlin 中开发 Android 应用程序,其中有付款功能,该功能位于活动的主 ui 线程中,但我想创建一个单独的付款活动并使用协程在其他 Ui 线程中处理它,我正在使用意图过滤器将此活动的数据传递到我的付款活动,但这已被弃用
startActivityForResult()
我该如何修复此问题请帮助我,这里是我的代码片段。
fun onClickJoin(view: View) {
if (binding.joinNowTxt.text.toString() == resources.getString(R.string.join_now)) {
val paymentIntent = Intent(this,PaymentActivity::class.java).apply {
putExtra("PAYMENT_AMOUNT",test_list[position].joinAmount.toFloat().toInt())
putExtra("TEST_ID",test_list[position].testId)
}
//this is deprecated
startActivityForResult(paymentIntent, PAYMENT_REQUEST_CODE)
} else {
bindingPayment.choosePaymentLayout.visibility = View.GONE
if (isAttemp == 2) {
val intent = Intent(applicationContext, AttemptTestActivity::class.java)
intent.putExtra("Test_Id", test_list[position].testId)
intent.putExtra("Category_Id", category_id)
intent.putExtra("Result_Auto_Publish", result_auto_publish)
Log.e("Intent Data", "Starting AttemptTestActivity")
startActivity(intent)
}
}
我需要此问题的帮助
以下是更新代码的方法
声明 ActivityResultLauncher:
private lateinit var paymentResultLauncher: ActivityResultLauncher<Intent>
在onCreate()中注册启动器:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Register the launcher
paymentResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
// Handle the result from PaymentActivity
val data: Intent? = result.data
val paymentStatus = data?.getStringExtra("PAYMENT_STATUS")
Log.d("Payment", "Payment status: $paymentStatus")
} else {
// Handle cancellation or failure
Log.d("Payment", "Payment failed or cancelled")
}
}
}
使用注册的启动器启动 PaymentActivity:
fun onClickJoin(view: View) {
if (binding.joinNowTxt.text.toString() == resources.getString(R.string.join_now)) {
val paymentIntent = Intent(this, PaymentActivity::class.java).apply {
putExtra("PAYMENT_AMOUNT", test_list[position].joinAmount.toFloat().toInt())
putExtra("TEST_ID", test_list[position].testId)
}
// Use the registered launcher instead of startActivityForResult()
paymentResultLauncher.launch(paymentIntent)
} else {
bindingPayment.choosePaymentLayout.visibility = View.GONE
if (isAttemp == 2) {
val intent = Intent(applicationContext, AttemptTestActivity::class.java)
intent.putExtra("Test_Id", test_list[position].testId)
intent.putExtra("Category_Id", category_id)
intent.putExtra("Result_Auto_Publish", result_auto_publish)
Log.e("Intent Data", "Starting AttemptTestActivity")
startActivity(intent)
}
}
}