startActivityForResult的文档中有这么一句话:
For example, if the activity you are launching uses the singleTask launch mode, it will not run in your task and thus you will immediately receive a cancel result.
意思是:比如说,如果你正加载的activity使用了singleTask的加载模式,它不会在你的栈中运行,而且这样你会马上收到一个取消的结果。
即在onActivityResult里马上得到一个RESULT_CANCEL.
他还补充说没有很好的补救方法。可以试试用监听广播的方法。
另一个*的问题中,有人直接回答了不能再singleInstance或singleTop模式下使用startActivityForResult()方法,不仅被采纳了,票数还不低。
剩下的一个*问题中,有人说把singleTask改成singleTop就会正常,得到高达59票并被采纳。实际上我用的就是singTop,可是onActivityResult还是无缘无故被调用了。
startActivityForResult的文档:
public void startActivityForResult (Intent intent, int requestCode, Bundle options)
Added in API level 16
Launch an activity for which you would like a result when it finished. When this activity exits, your onActivityResult() method will be called with the given requestCode. Using a negative requestCode is the same as calling startActivity(Intent) (the activity is not launched as a sub-activity).
加载一个Activity,当它结束时你会得到结果。当这个Activty退出了,你的onActivityResult()方法会根据给出的requestCode被调用。使用一个负的requestCode和调用startActivity(intent)一样(activity不被加载成子activity)
startActivityForResult(intent, 0);
是第二个参数的问题,该参数必须大于0才能在返回值,并激活onActivityResult方法。
我最开始是用的一个activity默认的常量:RESULT_OK,跟踪了代码后发现,该常量的值为-1,当然没法激活 onActivityResult方法了,随后随便修改为一个大于0的整数,程序即通跑成功。
Note that this method should only be used with Intent protocols that are defined to return a result. In other protocols (such as ACTION_MAIN or ACTION_VIEW), you may not get the result when you expect. For example, if the activity you are launching uses the singleTask launch mode, it will not run in your task and thus you will immediately receive a cancel result.
注意这个方法只能用于被定义要返回结果的Intent协议。在其他协议中(譬如ACTION_MAIN或ACTION_VIEW),你可能在你想得到结果时得不到。比如,当你正载入的Activity使用的singleTask加载模式,它不会在你的栈中运行,这样你会立马得到一个取消的结果。
As a special case, if you call startActivityForResult() with a requestCode >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your activity, then your window will not be displayed until a result is returned back from the started activity. This is to avoid visible flickering when redirecting to another activity.
有一个特例是,当你在初始的onCreate()方法或onResume()方法中用一个大于等于0的请求码调用startActivityForResult(),你的窗口在被启动的Activity返回结果前不会显示。这是为了避免跳转到另一Activity时可见的闪烁。
This method throws ActivityNotFoundException if there was no Activity found to run the given Intent.
如果运行所给Intent的Activity没被找到,该方法会抛出ActivityNotFoundException异常。