以前在使用startActivityForResult()的时候,一直都非常顺利,今天却发现出现了一个奇怪的情况。
问题描述如下:
1、我在执行完startActivityForResult()函数后,还没有启动目标Activity,当前activity中的onActivityResult()方法却先执行了。
2、我在执行完目标Activity,返回的时候,却发现onActivityResult()方法不执行。
就那么几行代码,找了好久没有找到原因。经过搜索一番,发现问题出在Activity的launchMode上。经过测试发现原来在调用startActivityForResult的时候,目标Activity的启动模式只能是launchMode="standard" 和 “singleTop”模式,不能是其他2种模式。
去查看android文档,发现有如下描述:
Note that this method should only be used with Intent protocols that are defined to return a result. In other protocols (such asACTION_MAINorACTION_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.
我们在使用singleTask或者singleInstance的时候,会新起一个task,这个时候我们在返回的时候就会返回一个cancel结果。同时从Locat中会看到如下警告:
Activity is launching as a new task, so cancelling activity result.
来源:oschina
链接:https://my.oschina.net/u/937713/blog/219735