Android startActivityForResult 过时的替代方法。registerForActivityResult用法

从A_Activity跳转到B_Activity,用Intent传递数据,B页面处理完返回数据到A

activity_a.xml

<?xml version="1.0" encoding="utf-8"?>

<Button
    android:id="@+id/button_to_b"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="向B页面发送数据"/>
<TextView
    android:id="@+id/textview_from_b"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="30sp"/>

activity_b.xml

<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:id="@+id/textview_from_a"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="这是第二页"
    android:textSize="30sp"/>
<Button
    android:id="@+id/button_to_a"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="返回应答数据"/>

DateUtility.java

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DateUtility {
public static String getNowTimeZH() {
//xxxx年xx月xx日hh:mm:ss hh:mm:ss hh:mm:ss:SSS
//Date date = new Date();
SimpleDateFormat sf = new SimpleDateFormat(“yyyy年MM月dd日hh:mm:ss”, Locale.CHINA);
return sf.format(new Date());
}

//获取当前日期时间
public static String getNowDateTime() {
    SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
    return sf.format(new Date());
}

//获取当前时间
public static String getNowTime() {
    SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
    return sf.format(new Date());
}

//获取当前时间,含毫秒
public static String getNowTimeDetail() {
    SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss.SSS", Locale.CHINA);
    return sf.format(new Date());
}

}

A_Activity.java

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

public class A_Activity extends AppCompatActivity {
private Button btnToB;
private TextView tv_fromB;
private ActivityResultLauncher resultLauncher;//定义一个Activity结果启动器对象。提示参数化类“ActivityResultLauncher”的原始使用

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_a);

    tv_fromB = findViewById(R.id.textview_from_b);
    btnToB = findViewById(R.id.button_to_b);
    //第2步、先写从B_Activity来的邮递员B扛来的邮包中,应该会有哪些信息,接收并显示
    // 这个registerForActivityResult方法要写在Activity的onCreate方法里(在Activity创建的时候就要创建出来,不能等到使用的时候再创建,不然会报错
    //也不能放在btnToB.setOnClickListener,放在那里也会出错
    resultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                        Bundle bundle = result.getData().getExtras();//获取从B_Activity来的邮递员B扛的邮包
                        String response_fromB_time = bundle.getString("response_fromB_time"); //从包裹中取出信封上写“response_fromB_time”的信件的内容
                        String response_fromB_content = bundle.getString("response_fromB_content");//从包裹中取出信封上写“response_fromB_content”的信件的内容
                        String desc = String.format("收到B答复的消息:\n应答时间为:%s\n应答内容为:%s", response_fromB_time, response_fromB_content);//拼接
                        tv_fromB.setText(desc); //显示
                    }
                }
            });

    //第1步、点击按钮,向B_Activity发出消息
    btnToB.setOnClickListener(v -> {//lamda表达式,代替new View.onClickListener和onclick()方法
        Intent intent_A = new Intent(A_Activity.this, B_Activity.class);//创建邮递员A,指明从A_Activity出发,到B_Activity
        Bundle bundle = new Bundle(); //创建邮递员A要扛的空邮包
        bundle.putString("send_toPageB_time", DateUtility.getNowTimeZH());//向邮包放第一封信,信封上写“send_toPageB_time”,内容为DateUtility.getNowTime()
        bundle.putString("send_toPageB_content", "今天天气怎么样?");//向邮包放第一封信,信封上写“send_toPageB_content”,内容为"今天天气怎么样?"
        intent_A.putExtras(bundle); //邮递员A扛起邮包
        resultLauncher.launch(intent_A);//邮递员A出发
    });
}

}

B_Activity.java

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

public class B_Activity extends AppCompatActivity {
private Button btnToA;
private TextView tv_fromA;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b);

    tv_fromA = findViewById(R.id.textview_from_a);
    btnToA = findViewById(R.id.button_to_a);

    //第3步、接收A_Activity发来的消息并显示
    Bundle bundle = getIntent().getExtras();//获取邮递员A扛来的邮包
    String send_toPageB_time = bundle.getString("send_toPageB_time");//从包裹中取出信封上写“send_toPageB_time”的信件的内容
    String send_toPageB_content = bundle.getString("send_toPageB_content");//从包裹中取出信封上写“send_toPageB_content”的信件的内容
    String desc = String.format("收到A发来问候消息:\n发出时间为:%s\n发出内容为:%s", send_toPageB_time, send_toPageB_content);//拼接
    tv_fromA.setText(desc);//显示

    //第4步、点击按钮向A_Activity发送消息
    btnToA.setOnClickListener(v -> {
        Intent intent_B = new Intent();//创建邮递员B
        Bundle bundle1 = new Bundle();//创建邮递员B要扛的空邮包
        bundle1.putString("response_fromB_time", DateUtility.getNowTime());//向邮包放第一封信,信封上写“response_fromB_time”,内容为DateUtility.getNowTime()
        bundle1.putString("response_fromB_content", "今天晴空万里,阳光灿烂!");//向邮包放第一封信,信封上写“response_fromB_content”,内容为DateUtility.getNowTime()
        intent_B.putExtras(bundle1);//邮递员B扛起邮包
        setResult(Activity.RESULT_OK, intent_B);//邮递员A出发,同时携带上B_Activity已经接收A_Activity数据并处理成功的信息RESULT_OK。RESULT_OK表示处理成功
        finish(); //销毁B_Activity,向安卓操作系统归还内存、CPU等系统资源
    });
}

}

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值