startActivityForResult 和startActivity的区别

本文详细介绍了Android开发中Activity之间的交互方式,特别是startActivityForResult方法的使用,包括如何请求数据及如何接收返回的数据。这对于理解Android应用内部的工作原理非常关键。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 Android Develop中如下描述

The startActivity(Intent) method is used to start a new activity, which will be placed at the top of the activity stack. It takes a single argument, an Intent, which describes the activity to be executed.

Sometimes you want to get a result back from an activity when it ends. For example, you may start an activity that lets the user pick a person in a list of contacts; when it ends, it returns the person that was selected. To do this, you call the startActivityForResult(Intent, int) version with a second integer parameter identifying the call. The result will come back through your onActivityResult(int, int, Intent) method.

When an activity exits, it can call setResult(int) to return data back to its parent. It must always supply a result code, which can be the standard results RESULT_CANCELED, RESULT_OK, or any custom values starting at RESULT_FIRST_USER. In addition, it can optionally return back an Intent containing any additional data it wants. All of this information appears back on the parent's Activity.onActivityResult(), along with the integer identifier it originally supplied.

 

startActivityForResult与startActivity的不同之处在于,后者仅仅是跳转到目标页面,若是想跳回当前页面,则必须再使用一次startActivity。而通过使用startActivityForResult可以一次性完成这项任务,这个方法有两个参数,第一个参数是要切换的Intent,第二个参数是一个整数,用做标记的作用。当程序执行到这段代码的时候,页面会跳转到要切换的Activity,而当这个Activity被关闭以后(this.finish()),程序会自动跳转会第一个Activity,并调用前一个Activity的onActivityResult方法。所以在第一个Activity中必须覆盖onActivityResult方法。通过获取onActivityResult方法中的第一个参数(requestCode)判断该参数是不是和前面在startActivityForResult中设置的标记相等。作为是否正确执行的依据,同时在onActivityResult中取出数据进行处理。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值