startActivityForResult 和startActivity的区别

来源:互联网 发布:蘑菇街销量软件 编辑:程序博客网 时间:2024/04/29 21:48

 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'sActivity.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中取出数据进行处理。