咸鱼

咸鱼是以盐腌渍后,晒干的鱼

0%

Android带结果的启动Activity推荐使用registerForActivityResult

startActivityForResult过期

一直都是这样启动一个带返回结果的Activity

1
2
3
4
5
6
7
8
val intent = Intent(this, VideoPlaybackListPPCSActivity::class.java).apply {
this.putExtra("data",111)
}

// 此方法已过期
// Deprecated
// use registerForActivityResult(ActivityResultContract, ActivityResultCallback) passing in a androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult object for the ActivityResultContract.
startActivityForResult(intent,10090)

使用registerForActivityResult跳转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//初始化不能在按键事件等地方执行,建议在onCreate执行
val launcher = registerForActivityResult(object: ActivityResultContract<String,String>(){
override fun createIntent(context: Context, input: String?): Intent {

return Intent(this@VideoPlayerPPCSActivity, VideoPlaybackListPPCSActivity::class.java).apply{
intent.extras?.let { ext ->
ext.putInt("session",remoteCamera.getSession())
this.putExtras(ext)
}
}
}
override fun parseResult(resultCode: Int, intent: Intent?): String {

//解析Intent中的数据,返回给onActivityResult
//这里不需要数据
return "ok"
}
},object: ActivityResultCallback<String>{
override fun onActivityResult(result: String?) {

//拿到数据
}
})


// 需要跳转时,这样执行
val intent = Intent(this, VideoPlaybackListPPCSActivity::class.java).apply {
this.putExtra("data",111)
}
launcher.launch(intent)

简化

Deprecated
use registerForActivityResult(ActivityResultContract, ActivityResultCallback) passing in a androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult object for the ActivityResultContract.

如果仅仅只跳转Activity,可以用ActivityResultContracts.StartActivityForResult简化为以下代码:

1
2
3
4
5
6
7
8
9
10
11

// 注册
private lateinit var launcher: ActivityResultLauncher<Intent>
launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
// lamda 简化了ActivityResultCallback
// 这里处理结果
}

....
//启动Activity
launcher.launch(intent)