The processing method after Android activity returns no longer supports startActivityForResult()

To realize interaction between activities and return to the previous activity, the traditional method is to use startActivityForResult to start the activity, and return the data of the previous activity and other processing in the onActivityResult function. The specific code is as follows:

class MainActivity : AppCompatActivity() {
   lateinit var binding:ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         binding = ActivityMainBinding.inflate(layoutInflater)
         setContentView(binding.root)
        binding.firstBtn.setOnClickListener {
            turnTo(FirstActivity::class.java,1)       			//跳转到FirstActivity活动
        }
       binding.secondBtn.setOnClickListener {
            turnTo(SecondActivity::class.java,2)     			//跳转到SecondActivity活动
        }
    }
private fun <T> turnTo(c:Class<T>,requestCode:Int){
        val intent = Intent(MainActivity@this,c) 	   		//定义意图
        startActivityForResult(intent,requestCode)   		//启动活动,设置请求码
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode== Activity.RESULT_OK){
            when(requestCode){
                1->{	                                                                //从FirstActivity返回
                    val receivedData = data?.getStringExtra("info")
                    Toast.makeText(MainActivity@this,"接收:$receivedData",
                                  Toast.LENGTH_LONG).show()
                }
                2->{                                                                      //从SecondActivity返回
                    Toast.makeText(MainActivity@this, resources.getString(R.string.title_frm_second),
                                   Toast.LENGTH_LONG).show()
                }
            }
        }
    }
}

However, this method of processing is no longer supported when the appcompat library is upgraded to version 1.3.0 or higher. The reason is that the official recommendation is to use the Activity Result API. In the new version, activities interact with each other and need to return to the previous activity. At this time, the code is adjusted to: In the previous activity, the code is similar
:

class MainActivity : AppCompatActivity() {
    lateinit var resultLauncher: ActivityResultLauncher<Intent>
    lateinit var binding:ActivityMainBinding
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        resultLauncher =registerForActivityResult(
            ActivityResultContracts.StartActivityForResult(),
                ActivityResultCallback {
                    if(it.resultCode== Activity.RESULT_OK){
                         Toast.makeText(MainActivity@this, 
                                    it.data?.getStringExtra("FrmInfo"),
                                   Toast.LENGTH_LONG).show()
                    }
             })
          binding.firstBtn.setOnClickListener {
            turnActivity(FirstActivity::class.java,"To FirstActivity")      			
            //跳转到FirstActivity活动
        }
       binding.secondBtn.setOnClickListener {
            turnTo(SecondActivity::class.java,"To SecondActivity")     			
            //跳转到SecondActivity活动
        }   
    }
    private fun<T> turnActivity(c:Class<T>,info:String){
        //跳转到下一个活动
        val intent = Intent(this,c)
         intent.putExtra("DATA",info)
        resultLauncher.launch(intent)**
    }
}

The registerForActivityResult() activity result registration callback function receives two parameters:
(1) The first parameter: It is the Contract type, which defines the input type required to generate the result and the output type of the result. These APIs provide default contracts for basic intent operations such as taking pictures and requesting permissions. Its function is to request data from another Activity;
(2) The second parameter: It is ActivityResultCallback, which is a single method interface with an onActivityResult() method. It can accept objects of the output type defined in ActivityResultContract and is expressed as a Lambda Expression, when a result is returned, it will be called back here, where the data will be obtained and processed.

In the jumped activity, the code is similar:

class FirstActivity : AppCompatActivity() {
    lateinit var binding:ActivityFirstBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
      
        binding = ActivityFirstBinding.inflate(layoutInflater)
        //接收从MainActivity发送的数据
        binding.firstTxt.text = intent.getStringExtra("DATA")
        binding.returnBtn.setOnClickListener {
            //返回上一个活动MainActivity
            val intent = Intent()
            intent.putExtra("FrmInfo","FirstActivity返回MainActivity")

            setResult(Activity.RESULT_OK,intent)
            finish()
        }
        setContentView(binding.root)
    }
}

references:

"Get activity results"
https://developer.android.google.cn/training/basics/intents/result?hl=zh-cn

Guess you like

Origin blog.csdn.net/userhu2012/article/details/127251385