appcompat 升级到1.3.0 及以上版本,startActivityForResult()被标为废弃了,官方推荐使用Activity Result API来实现
Activity Result API 的简单使用
1.从A Activity跳转到B Activity,B Activity返回数据
A Activity的代码
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<TextView>(R.id.tv_hello).setOnClickListener {
useNewApi()
}
}
private fun useNewApi(){
//还是像之前的一样,创建一个intent
val intent = Intent(this@MainActivity,SecondActivity::class.java)
//将intent传递给registerForActivityResult()返回的实例的launch()方法
requestDataLauncher.launch(intent)
}
//activity的跳转使用ActivityResultContracts
private val requestDataLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
//在此处获取SecondActivity返回的值,此处的返回值类型是ActivityResult,它有两个字段,一个是resultCode,一个是带着从SecondActivity返回数据的Intent
if (result.resultCode == RESULT_OK){
Log.d("MainActivity","secondActivity result = ${result?.data?.getIntExtra("action",-15)}")
}
}
}
B Activity的代码
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second_layout)
findViewById<TextView>(R.id.tv_return).setOnClickListener {
//返回数据的地方还是跟原来一样
val intent = Intent()
intent.putExtra("action",15)
setResult(RESULT_OK,intent)
finish()
}
}
}
2.registerForActivityResult()请求权限
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<TextView>(R.id.tv_hello).setOnClickListener {
useNewApiRequestPermission()
}
}
private fun useNewApiRequestPermission(){
//此处直接传入需要的权限对应的字符串
requestPermissionLauncher.launch(Manifest.permission.CAMERA)
}
//此处还是使用registerForActivityResult,与跳转到其他activity不同的是,第一个参数改为ActivityResultContracts.RequestPermission的实例
private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
//回调返回值也跟activity跳转的不同,此处返回的是boolean值
Log.d("MainActivity","requestPermissionResult = $granted")
if (granted){
}else{
}
}
}
上面两个例子,都是通过registerForActivityResult获取一个实例,再用这个实例调用launch()来实现,不同的是第一个参数contract,启动activity用的是ActivityResultContracts.StartActivityForResult,请求权限的用的ActivityResultContracts.RequestPermission
来看看有哪些contract。
画红线的是上面两个例子用的到,需要什么功能再选择相应的contracts即可