过早地调用 onActivityResult()

我从我的工人活动开始 Activity(PreferenceActivity的后代)如下:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1458)
loadInfo();
}


void showSettingsDialog()
{
startActivityForResult(new Intent().setClass(this, MyConfigure.class), 1458);
}

MyConfigure类没有任何 setResult()调用。实际上,除了 OnCreate()以外,MyConfigure类没有任何代码,它使用 addPreferencesFromResource加载首选项。

现在 onActivityResult1458requestCode一起被过早地调用,就在 MyConfigure活动运行之后。在1.6和2.1仿真器以及2.1设备上进行了测试。有没有打到 setResult()的电话埋在 PreferenceActivity的某个地方?否则怎么解释这个过早的电话呢?

30201 次浏览

Again as in Mayra's comment, setResult() has nothing to do with your problem. for some reason, MyConfigure class finishes itself and when it happens PreferenceActivity just assumes that there might be a result from MyConfigure because that's how you wrote the code.

this also happens when you force back any activity thats started with startActivityForResult()...

So, I think it's better to focus on why your MyConfigure class is forcibly finished.

This is fixed by changing the launch mode to singleTop:

    <activity
android:name=".MainActivity"
android:launchMode="singleTop">

There's a bug / feature (?) in Android, which immediately reports result (which has not been set yet) for Activity, declared as singleTask (despite the fact that the activity continues to run). If we change launchMode of the parent activity from singleTask to singleTop, everything works as expected - result is reported only after the activity is finished. While this behavior has certain explanation (only one singleTask activity can exist and there can happen multiple waiters for it), this is still a not logical restriction for me.

I just removed all my custom "android:launchMode" from my Activity and everything worked like a charm. It is not a good idea change this when you don't know EXACTLY what Android is understanding... Android is a little tricky in this way.

I solved my problem after removing intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); before calling fragment.startActivityForResult(intent, 0);.

This happened to me when the intent had the Intent.FLAG_RECEIVER_FOREGROUND flag set.

(Yes, that flag isn't activity-related, but I had it on all my intents as part of a shotgun solution to a different problem.)