关于startActivityForResult

本文深入解析了Android中使用startActivityForResult函数启动Activity后,其在完成时调用启动者Activity的onActivityResult方法的过程。讨论了该函数的调用限制,如requestCode、launchmode和Intent action的条件,以及一个特殊的使用场景,即在onCreate/onResume函数中启动Activity以避免闪烁问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很偶然的一次,发现在有些手机上startActivityForResult函数,在启动activity之后立即调用了,而在另一些手机上表现正常,十分不解,在网上查找后知道了原因,更详细的解释在api说明中:

public void startActivityForResult (Intent intent, int requestCode, Bundle options);

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).

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.

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.

大致意思是,使用这个函数启动的activity在其finish之后,会调用启动者的onActivityResult()函数,通知启动者自己已经结束了,然后让启动者去处理一些事情。
这个函数的调用限制:

- requestCode需要大于等于0,使用一个小于0的值,那么就相当于startActivity函数,不会有任何返回
- 启动的Activity的launch mode是能够返回的,不能是singleTask
- Intent的action必须是能够返回的,不能是ACTION_MAIN,ACTION_VIEW等

然后还列举了一使用这个函数的特殊场景:
可以在onCreate/onResume函数中使用startActivityForResult启动其他的Activity,那么启动者Activity将不会被显示,直到被启动的Activity返回。这样做可以避免在onCreate/onResume中直接调用startActivity时导致的闪烁问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值