Android利用startActivityForResult返回数据到前一个Activity

在Android里面,从一个Activity跳转到另一个Activity、再返回,前一个Activity默认是能够保存数据和状态的。但这次我想通过利用startActivityForResult达到相同的目的,虽然看起来变复杂了,但可以探索下startActivityForResult背后的原理和使用注意事项。

要实现的功能如下:

从Activity A将数据传到Activity B,再从Activity B中获取数据后,再传回Activity A。在Activity B中添加一个“回到上一页”的Button,返回到Activity A之后,需要保留之前输入的相关信息,我们用startActivityForResult来拉起Activity B,这样,Activity A就会有一个等待Activity B的返回。

具体步骤如下:

  1. 在Activity A中有一个Button,点击Button后,获取要传到Activity B的数据,将数据封装到Bundle中,再调用startActivityForResult将数据传到Activity B
  2. Activity A 重写onActivityResult函数,判断requestCode和resultCode是否是我们预期的结果,如果是,那么从Bundle中获取数据,重新显示在Activity A中
  3. 在Activity B中获取Activity A传过去的Intent对象,并取出Bundle对象,再从Bundle中取出数据字段,显示在当前页面
  4. Activity B中也有一个Button,点击Button后,调用setResult传回结果,并关闭当前页面。因此,看起来的效果就是回到了Activity A

源码如下:

1、Activity A的实现:

public class ExampleActivity extends Activity {

 private EditText mEditText;
 private RadioButton mRb1;
 private RadioButton mRb2;

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

 Button button = findViewById(R.id.buttonGoToLayout2);
 button.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  mEditText = findViewById(R.id.editText);
  // 获取输入的身高
  double height = Double.parseDouble(mEditText.getText().toString());

  // 获取性别
  String gender = "";
  mRb1 = findViewById(R.id.radioButtonMale);
  mRb2 = findViewById(R.id.radioButtonFemale);
  if (mRb1.isChecked()) {
   gender = "M";
  } else {
   gender = "F";
  }

  Intent intent = new Intent(ExampleActivity.this, SecondActivity.class);
  // 将数据传入第二个Activity
  Bundle bundle = new Bundle();
  bundle.putDouble("height", height);
  bundle.putString("gender", gender);
  intent.putExtras(bundle);

  startActivityForResult(intent, 0);
  }
 });
 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 super.onActivityResult(requestCode, resultCode, data);
 if (resultCode == RESULT_OK && requestCode == 0) {
  Bundle bundle = data.getExtras();
  double height = bundle.getDouble("height");
  String gender = bundle.getString("gender");

  mEditText.setText("" + height);
  if (gender.equals("M")) {
  mRb1.setChecked(true);
  } else {
  mRb2.setChecked(true);
  }
 }
 }
}

2、布局文件main_page_layout.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:layout_gravity="center">

 <TextView
  android:id="@+id/textView1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="计算标准体重"
  android:paddingTop="20dp"
  android:paddingLeft="20dp"
  android:textSize="30sp"/>

 <TextView
  android:text="性别:"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:id="@+id/textView3"
  android:layout_alignStart="@id/textView1" android:layout_marginTop="38dp"
  android:layout_below="@id/textView1" android:layout_marginStart="46dp"/>

 <TextView
  android:text="身高:"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:id="@+id/textView4"
  android:layout_alignStart="@id/textView1" android:layout_marginStart="46dp"
  android:layout_below="@id/textView3" android:layout_marginTop="29dp"/>

 <EditText android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:id="@+id/editText"
  android:layout_toEndOf="@id/textView4"
  android:layout_marginStart="36dp"
  android:autofillHints="@string/app_name"
  android:hint="0"
  android:layout_alignBaseline="@id/textView4"/>

 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:text="厘米"
  android:layout_alignBaseline="@id/editText"
  android:layout_toRightOf="@id/editText"
  android:layout_marginStart="10dp" />

 <RadioButton
  android:layout_below="@id/textView1"
  android:id="@+id/radioButtonMale"
  android:text="男"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_alignStart="@id/textView1" android:layout_marginTop="30dp"
  android:layout_marginStart="113dp"/>

 <RadioButton
  android:id="@+id/radioButtonFemale"
  android:text="女"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_below="@id/textView1"
  android:layout_toEndOf="@id/radioButtonMale"
  android:layout_marginLeft="15dp" android:layout_marginTop="30dp" android:layout_marginStart="49dp"/>

 <Button
  android:text="计算"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/buttonGoToLayout2"
  android:layout_marginTop="90dp"
  android:layout_below="@id/radioButtonMale"
  android:layout_alignStart="@id/textView1" android:layout_marginStart="92dp"/>
</RelativeLayout>

3、Activity B的实现:

public class SecondActivity extends Activity {
 private Intent mIntent;
 private Bundle mBundle;

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

 mIntent = getIntent();
 mBundle = mIntent.getExtras();

 // 记得判空
 if (mBundle == null) {
  return;
 }

 // 获取Bundle中的数据
 double height = mBundle.getDouble("height");
 String gender = mBundle.getString("gender");

 // 判断性别
 String genderText = "";
 if (gender.equals("M")) {
  genderText = "男性";
 } else {
  genderText = "女性";
 }

 // 获取标准体重
 String weight = getWeight(gender, height);

 // 设置需要显示的文字内容
 TextView textView = findViewById(R.id.textView2);
 textView.setText("你是一位" + genderText + "\n你的身高是" + height + "厘米\n你的标准体重是" + weight + "公斤");

 Button button = findViewById(R.id.buttonGoBack);
 button.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  // 设置结果,并关闭页面
  setResult(RESULT_OK, mIntent);
  finish();
  }
 });
 }

 // 四舍五入格式化
 private String format(double num) {
 NumberFormat formatter = new DecimalFormat("0.00");
 return formatter.format(num);
 }

 // 计算标准体重的方法
 private String getWeight(String gender, double height) {
 String weight = "";
 if (gender.equals("M")) {
  weight = format((height - 80) * 0.7);
 } else {
  weight = format((height - 70) * 0.6);
 }
 return weight;
 }
}

4、Activity B的布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
 <TextView
  android:text="This is the second layout"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/textView2"
  android:paddingTop="30dp"
  android:paddingStart="50dp"/>
 <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:id="@+id/buttonGoBack"
  android:text="回到上一页"
  android:layout_alignStart="@id/textView2"
  android:layout_below="@id/textView2"
  android:layout_marginTop="54dp" android:layout_marginStart="52dp"/>
</RelativeLayout>

不过这里有3个地方需要注意:

1.startActivityForResult的第二个参数requestCode传的是0,那么我们分别看下传递的值小于0和大于0是什么结果:
(1)传一个小于0的值,比如-1:等同于调用 startActivity,onActivityResult不会被调用
(2)传一个大于0的值,比如1:效果等同于传0,onActivityResult的第一个参数正是我们通过startActivityForResult传递的requestCode

2.onActivityResult的第二个参数resultCode:它是第二个activity通过setResult返回的,常用的取值有2个:RESULT_CANCELED、RESULT_OK
(1)RESULT_CANCELED:Activity B拉起失败,比如crash
(2)RESULT_OK:Activity B操作成功后的返回值

还有一个不太常用的取值:RESULT_FIRST_USER,Android源码对这个取值的定义是“user-defined activity results”(用户自定义的),我在源码中全局搜索了下,用的地方不多,挑了一两个使用的地方:

(1)PackageInstaller下面的InstallFailed.java(安装apk失败的相关页面)

protected void onCreate(@Nullable Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 int statusCode = getIntent().getIntExtra(PackageInstaller.EXTRA_STATUS,
  PackageInstaller.STATUS_FAILURE);
 if (getIntent().getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false)) {
  // ……..
  setResult(Activity.RESULT_FIRST_USER, result);
  finish();
 }

(2)PackageInstaller下面的InstallStaging.java

private void showError() {
 (new ErrorDialog()).showAllowingStateLoss(getFragmentManager(), "error");
 // …….
 setResult(RESULT_FIRST_USER, result);
}

PackageInstaller下面的UninstallerActivity.java(卸载apk的相关页面):在onCreate方法里面有多处设置为RESULT_FIRST_USER。
因此,我的理解是业务自身在一些错误或无效的场景下使用,由业务自己定义。

3. 如果启动Activity B时设置了new_task启动模式,进入Activity B后,Activity A会立即回调onActivityResult,而且resultCode是0;从Activity B setResult返回后,不再有onActivityResult的回调!

以上就是Android利用startActivityForResult返回数据到前一个Activity的详细内容,更多关于Android 返回数据到前一个Activity的资料请关注我们其它相关文章!

(0)

相关推荐

  • Android实现左滑退出Activity的完美封装

    1:定义一个自己的父级容器,让它继承自一个布局(LinearLayout.RelativeLayout都可以) public class SildingFinishLayout extends RelativeLayout implements View.OnTouchListener { /** * SildingFinishLayout布局的父布局 */ private ViewGroup mParentView; /** * 处理滑动逻辑的View */ private View touc

  • 关于android连续点击出现多个Activity界面的解决方法

    前言 开始始学习android,对android的启动模式没有什么了解,就使用了时间判断是否重复点击了两次按钮,启动另外的activity界面,这样的控制方法,有时候会失效,比如,两秒钟还未启动另外的activity,那么又可以重复点击.所以,就调整为android的启动模式来控制重复出现多个acitvity. 一.通过时间控制点击次数: 这种方式对应控制网络请求不错. public class NoDoubleClickUtil { private static long lastClickT

  • Android实现音乐播放进度条传递信息的两种方式(在service和activity中)

    实现播放时的进度条显示,或是定时从service获取某些信息,是我们日常开发中经常遇到的需求,下面介绍当音乐再service中运行时,activity如果获取音乐进度信息的两种方式: 一.在activity中建立消息接收机制 我们需要在activity中建立一个用于接收信息的handler(handler简单的说是在android中可以发送消息和也可以处理消息的一种机制,当然它的用途更加强大,有时间可以去自己了解) 我们需要在onCreate方法之前添加handler,这样才能保证当我们的act

  • AndroidX下使用Activity和Fragment的变化详解

    过去的一段时间,AndroidX 软件包下的 Activity/Fragmet 的 API 发生了很多变化.让我们看看它们是如何提升Android 的开发效率以及如何适应当下流行的编程规则和模式. 本文中描述的所有功能现在都可以在稳定的 AndroidX 软件包中使用,它们在去年均已发布或移至稳定版本. 在构造器中传入布局 ID 从 AndroidX  AppCompat 1.1.0 和 Fragment 1.1.0 ( 译者注:AppCompat 包含 Fragment,且 Fragment

  • 通过实例解析android Activity启动过程

    注:只是说明启动activity的过程(ActivityThread如何与ActivityManagerService简称AmS进行进程间通信调用全过程),不解析android从zygote(受精卵)到整个系统服务的启动 具体来讲,启动activity的方式有以下几种: 在应用程序中startActivity()或startActivityForResult()方法启动指定activity 在HOME(桌面)程序中单击应用图标,启动新的activity 按"BACK"键结束当前acti

  • 详解Android Activity的启动流程

    前言 activity启动的流程分为两部分:一是在activity中通过startActivity(Intent intent)方法启动一个Activity:二是我们在桌面通过点击应用图标启动一个App然后显示Activity:第二种方式相较于第一种方式更加全面,所以本文会以第二种流程来分析. 简要 我们手机的桌面是一个叫做Launcher的Activity,它罗列了手机中的应用图标,图标中包含安装apk时解析的应用默认启动页等信息.在点击应用图标时,即将要启动的App和Launcher.AMS

  • Android IPC机制ACtivity绑定Service通信代码实例

    Binder通信过程类似于TCP/IP服务连接过程binder四大架构Server(服务器),Client(客户端),ServiceManager(DNS)以及Binder驱动(路由器) 其中Server,Client,ServiceManager运行于用户空间,驱动运行于内核空间.这四个角色的关系和互联网类似:Server是服务器,Client是客户终端,SMgr是域名服务器(DNS),驱动是路由器. book.java package com.example.android_binder_t

  • Android Activity的4种启动模式图文介绍

    前言 记得第一次探讨Activity的启动模式,是在2017年8月份,那个时候对一年后走出校门的未来很是憧憬,时间真快,已经毕业四个月,工作和生活也都趋于稳定. 一.小前言 相信很多人和我一样,在初学Android甚至初入职场的时候不了解Acticity的启动模式,或者为了面试刷题刷到了,但并不理解启动模式的作用,以及如何正确的使用启动模式而不是所有的都是用默认模式. 二.Activity启动模式简介 Activity有四种启动模式,standard.singleTop.singleTask.s

  • Android 开发使用Activity实现加载等待界面功能示例

    本文实例讲述了Android 开发使用Activity实现加载等待界面功能.分享给大家供大家参考,具体如下: 实现加载等待界面我用了两种方式,一种是用PopupWindow实现,另一种便是用Activity实现.用PopupWindow实现方法请见我的另一篇博客: android使用PopupWindow实现加载等待界面 好了,下面开始.先上效果: 基本原理就是在主界面点击按钮(以登录按钮为例)之后,打开一个新的Activity,此Activity以对话框形式展示.首先,主界面(一个登录按钮以及

  • Android用tabhost实现 界面切换,每个界面为一个独立的activity操作

    我就废话不多说了,大家还是直接看代码吧~ // 要extends TabActivity public class Main_activity extends TabActivity { private TabHost tabHost;// 建立Tabhost控件 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tabHost = getTabHost(); addT

  • Android非异常情况下的Activity生命周期分析

    Activity非异常情况下的生命周期是指,用户正常参与UI交互的情况下,Activity所经过的生命周期的改变:一般情况下,Activity会经过以下几个生命周期. 1.OnCreate(): 表示Activity正在创建,这个是生命周期的第一个方法,该方法只调用一次,在这个方法中,一般做变量初始化的操作,例如绑定一个Button控件的Id等. 2.onRestart(): 表示Activity正在重新启动,一般情况下,如果最前面的Activity从不可见状态变为可见状态时,onRestart

随机推荐