Android 10(Q) multi-resume(多项恢复)带来的问题

问题描述:

在项目中,ActivityA启动ActivityB,ActivityB启动系统图片选择器,如果从系统图片选择器返回,这个时候ActivityA和ActivityB同时都会回调onResume方法,这个时候如果ActivityA中的onResume方法里有代码执行,而且又不希望在后台中执行就会出问题。

正常理解只有Activity在最上层或者可以获取焦点的情况下才会回调onResume,但是此时的ActivityA自从打开ActivityB后一直处于后台,ActivityB属于正常的全屏Activty,居然可以后台onResum?这种情况是我没有想到的,感觉颠覆了Activity的生命周期的理解

分析过程:

通过查阅Activity文档有如下表述

Called after onRestoreInstanceState(Bundle), onRestart(), or onPause(). This is usually a hint for your activity to start interacting with the user, which is a good indicator that the activity became active and ready to receive input. This sometimes could also be a transit state toward another resting state. For instance, an activity may be relaunched to onPause() due to configuration changes and the activity was visible, but wasn’t the top-most activity of an activity task. onResume() is guaranteed to be called before onPause() in this case which honors the activity lifecycle policy and the activity eventually rests in onPause().
On platform versions prior to Build.VERSION_CODES.Q this is also a good place to try to open exclusive-access devices or to get access to singleton resources. Starting with Build.VERSION_CODES.Q there can be multiple resumed activities in the system simultaneously, so onTopResumedActivityChanged(boolean) should be used for that purpose instead.

加粗部分意思是说从Android10 (Q)开始可能有多个activity同时resume,所以应该使用onTopResumedActivityChanged回调方法代替

那么问题又来了为啥Android 10会做出这样的改变呢,原来是为了兼容多窗口多屏幕,应用在上述设备同一个应用可以有多个resume状态下的Activity,具体可以参照官方文档

解决方法

如果你的Activity中原来是需要在onResume中做一些操作,但是不希望在后台触发,可以重写onTopResumedActivityChanged方法将原来onResume里执行的代码放入到下面执行。

override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) {
        super.onTopResumedActivityChanged(isTopResumedActivity)
        if (isTopResumedActivity) {
            //doSomething
        }
    }

这样又会带来一个新的问题,在Android10以下平台并不会回调onTopResumedActivityChanged这个方法,导致方法没有执行,需要在onResume方法里加上判断

override fun onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            refreshData()
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值