目录
1.情况说明
2.registerForActivityResult()的使用方法
startActivityForResult();函数过时
使用了
registerForActivityResult()进行了代替
数据来源
(2条消息) registerForActivityResult()的使用方法例子_发狂先生的博客-CSDN博客_registerforactivityresult用法
registerForActivityResult(ActivityResultContracts.TakeVideo())始终为空 - 我爱学习网 (5axxw.com)
registerForActivityResult 解决 startActivityForResult(Intent!, Int): Unit is deprecated. Deprecated in Java - Android - 大象笔记 (sunzhongwei.com)
https://blog.csdn.net/weixin_44618862/article/details/98209369
过时的OnActivityResult替代品-registerForActivityResult源码解析 - 未知用户的博客 (7449.github.io)
其中最为详细的在
(2条消息) registerForActivityResult()的使用方法例子_发狂先生的博客-CSDN博客_registerforactivityresult用法
registerForActivityResult 解决 startActivityForResult(Intent!, Int): Unit is deprecated. Deprecated in Java - Android - 大象笔记 (sunzhongwei.com)
数据来源
(2条消息) registerForActivityResult()的使用方法例子_发狂先生的博客-CSDN博客_registerforactivityresult用法

然后在Studio编写如下(自己加了一些)

在1中得java
package com.example.test1;import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;public class ChuangShuFrist extends AppCompatActivity {TextView text_message;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.chuangshufrist);text_message = (TextView) findViewById(R.id.cshi1);Button button_transfer1 = findViewById(R.id.cshibu11);//按钮1ActivityResultLauncher requestDataLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),result -> {Log.d("FirstActivity", result.getData().getStringExtra("data_return"));//tag表示标签信息,第二个参数表示要打印的信息,在这里表示可以在日志中看到该方法的执行});button_transfer1.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent=new Intent(ChuangShuFrist.this,ChuangShuSecond.class);requestDataLauncher.launch(intent);//用的是requestDataLauncher}});}}
在1得xml中
如下图

在2中得java
package com.example.test1;import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;public class ChuangShuSecond extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.chuangshusecond);Button button3=findViewById(R.id.but2);button3.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent=new Intent();intent.putExtra("data_return","Hello FirstActivity");setResult(RESULT_OK,intent);finish();}});}
}
在2得xml中
如下图

QQ录屏20221206140057
