OnActivityResult getting called twice in Android

心不动则不痛 提交于 2019-12-11 09:48:56

问题


I used this code to launch an activity:

 Intent intent = new Intent(this, OneTimeActivity.class);
 intent.putExtra(Constants.HOST_KEY, host);
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
 startActivityForResult(intent, 1000);

And for some reason my OnActivityResult() is called twice. Once when I first call startActivityForResult and once when the result actually ends. What's also weird is that the Intent data is always null, and the resultCode is always 0

Why is this happening? Shouldn't I only get a callback from OnActivityResult() once and also once? Shouldn't I get the result code I specify in setResult()?


回答1:


Well after about 2 hours of debugging it seems

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

Was the problem. Once I removed that everything worked as expected, which I guess makes sense. I can't clear the back stack and expect results to get returned correctly to the back stack I just cleared.




回答2:


In addition to etherton's answer, also check whether your activity is declared as singleTask or not.

Open AndroidManifest.xml and check for android:launchMode="singleTask" for your called activity. Remove this line and it will work as expected.

Note: If you really want your activity as singleTask then you have to handle your callbacks on your own.



来源:https://stackoverflow.com/questions/32237366/onactivityresult-getting-called-twice-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!