Keep track of some of the insights and questions about the return value of your activity to your superiors.
Requirements: Activity A-A and activity B, and an object instance (p) to b,activity B, some of P's data will be updated in real time, when the user returns a, you need to bring p back to a,
Method 1 Startactivityforresult ()
In A:
New Intent (This, B.class); Intent.putextra ("key", value); Startactivityforresult (Intent , Request_code);
* Note: Activity B cannot be started with (singletask), otherwise a will be directly affected by result_cancel, thus the return value cannot be returned.
Adding callback Method:onactivityresult () to a will require a judgment on Requestcode and Resultecode.
@Override protected void onactivityresult (intint resultcode, Intent data) { super. Onactivityresult (Requestcode, ResultCode, data);
Switch (ResultCode) {
Case activity.result_canceled:{}
Case ACTIVITY.RESULT_OK: {
if (Requestcode==request_code) {
P p = Data.getparcelableextra ("panel");
}
}
Default: ...
}
}
Activity B: Set the callback in the upper-left corner of activity
Public Booleanonoptionsitemselected (MenuItem item) {//Handle Item Selection Switch(Item.getitemid ()) { CaseAndroid. R.id.home:intent Intent= Navutils.getparentactivityintent ( This); Get Inent Intent.putextra ("Key", p); Put in P instance intent.addflags (Intent.flag_activity_clear_top); Set Intent flag Setresult (activity.result_ok,intent); Set ResultCode and Intent finish (); return true; default:return Super. onoptionsitemselected (item); } }
When you press return home or back, the Onresultactivity () callback in a will be called, a will be able to receive P (implements parcable)
Method 2: Use Onnewintent (), do not need to detect request_code and Result_code
A: StartActivity (Intent, b.class);
and add callback Onnewintent ()
@Override protectedvoid onnewintent (Intent Intent) { setintent (Intent ); = getintent (); ... Super . Onnewintent (intent); }
In B:
Intent.addflags (Intent.flag_activity_clear_top);
Intent.putextra (...);
Navunit.navigateupto (this,intent);
A will get a new intent.
Summary: StartActivity () and Startactivityforresult () can get the return value, but after the return callback different, the former with Onnewintent (), the latter with onresultactivity (). The latter can use Requestcode to control different passes and use ResultCode to represent states.
Android Activity Callback Value