问题
During testing I noticed that sometimes the finish() of my sub-activity doesn't execute onActivityResult. Most of the times it works okay, and I can't figure out, when and why this problem occurs.
Subactivity start:
public void launchSubActivity(Class<? extends Activity> subActivityClass, Bundle data,
OnSubActivityResult callback) {
Intent i = new Intent(this, subActivityClass);
if(data!=null) i.putExtras(data);
Random rand = new Random();
int correlationId = rand.nextInt();
_callbackMap.put(correlationId, callback);
startActivityForResult(i, correlationId);
}
Subactivity finish:
public void select() {
Bundle b = new Bundle();
b.putInt("YEAR", year_result);
b.putInt("MONTH", month_result);
b.putInt("DAY", day_result);
this.getIntent().putExtras(b);
this.setResult(RESULT_OK, this.getIntent());
this.finish();
}
onActivityResult (by Nazmul Idris):
/**
* this is the underlying implementation of the onActivityResult method that
* handles auto generation of correlationIds and adding/removing callback
* functors to handle the result
*/
@Override
protected void onActivityResult(int correlationId, int resultCode,
Intent data) {
Log.d(Prototype.TAG, "SimpleActivity Result "+resultCode);
try {
OnSubActivityResult callback = _callbackMap.get(correlationId);
switch (resultCode) {
case Activity.RESULT_CANCELED:
callback.onResultCancel(data);
_callbackMap.remove(correlationId);
break;
case Activity.RESULT_OK:
callback.onResultOkay(data);
_callbackMap.remove(correlationId);
break;
default:
Log.e(Prototype.TAG,
"Couldn't find callback handler for correlationId");
}
} catch (Exception e) {
Log
.e(Prototype.TAG,
"Problem processing result from sub-activity", e);
}
}
回答1:
Maybe you have some developer options like kill activity flag or limit background process.
Go to setting-> developer options unchecked Don't keep activities
and Background process limit
set to standard limit.
For extra information check https://stackoverflow.com/a/14195833/779408 and https://stackoverflow.com/a/11522468/779408
回答2:
Problem is "correlationId" < 0 :
/** use this method to launch the sub-Activity, and provide a functor to handle the result - ok or cancel */
public void launchSubActivity(Class subActivityClass, ResultCallbackIF callback) {
Intent i = new Intent(this, subActivityClass);
Random rand = new Random();
int correlationId = rand.nextInt();
/*
Values os correlationId:
1972479154
477929567
-1246508909 = NEGATIVE = INVALID!
*/
if (correlationId < 0)
correlationId *= -1;
_callbackMap.put(correlationId, callback);
startSubActivity(i, correlationId);
}
来源:https://stackoverflow.com/questions/4382910/onactivityresult-sometimes-not-called-when-sub-activity-finishes