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()
        }
    }

你可能感兴趣的:(问题记录,Android,android,onresume,multi-resume,多项恢复)