The difference between Android startactivityforresult and setresult

The difference between Android startactivityforresult and setresult

Startactivityforresult differs from startactivity in that:

1、startActivity( )

Just jump to the target page. If you want to jump back to the current page, you must use startactivity () again.

2、startActivityForResult( )

This task can be completed at one time. When the program executes this code, if it jumps from t1activity to the next text2activity, and when the text2activity calls the finish () method, the program will automatically jump back to t1activity and call the onactivityresult () method in the previous t1activity.

Correlation function:

Brief examples:

1. The method of startactivity (intent) is not used when jumping, but startactivityforresult (intent, 0)

2. Override the onactivityresult method to receive the data returned by B.

3. When returning data in B, use setresult method, and then call finish method.

When will setresult () of Android activity be called (key and difficult points)

If setresult is set in the activity from startactivityforresult, the result will not be returned to the parent's activity immediately. Only when the current activity is finished, the result will be sent to the parent's onactivityresult for processing!

If an activity wants to return data to the activity that started it, it can call the setresult () method. When to call the setresult () method to return data? Just look at the source code:

This code shows that the result returned by the activity is when it is finished, that is, the call to setresult () method must be before finish ().

If you call setResult () in the following method, you may not return to success: onPause (), onStop (), onDestroy ().

Because these method calls are not necessarily before finish. Of course, setresult called in oncreate () must be before finish

Press the back key to exit from an activity. Once you press back, Android will automatically call the finish () method of the activity, and then set the resultcode to result_ Cancel, no data will be returned

The solution is to capture the event of pressing back in the activity. After capturing it, first set result, and then call finish by yourself... Swallow the back event directly

Of course, you can call setresult in oncreate(), but I don't think this method is as good as overriding onbackpressed()

The above is the difference between Android startactivityforresult and setresult. If you have any questions, please leave a message or go to the community of this site for communication and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>