1. 程式人生 > >【Android】An activity without a UI must call finish() before onResume() complete

【Android】An activity without a UI must call finish() before onResume() complete

今天遇到這樣的一個bug,我的測試機是Android 7.0,經過追蹤得到一下關鍵出錯資訊:

An activity without a UI must call finish() before onResume() completes

很明顯這是因為當前的activity沒有UI造成的,通過檢視原始碼發現這個問題在6.0之前不存在,在6.0之後google對著快做了強制要求,下面是

Android 6.0相應的原始碼:

final void performResume() {
    performRestart();
    mFragments.execPendingActions();
    mLastNonConfigurationInstances = null
; mCalled = false; // mResumed is set by the instrumentation mInstrumentation.callActivityOnResume(this); if (!mCalled) { throw new SuperNotCalledException( "Activity " + mComponent.toShortString() + " did not call through to super.onResume()"); } // invisible activities must be finished before onResume() completes
if (!mVisibleFromClient && !mFinished) { Log.w(TAG, "An activity without a UI must call finish() before onResume() completes"); if (getApplicationInfo().targetSdkVersion > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) { throw new IllegalStateException( "Activity "
+ mComponent.toShortString() + " did not call finish() prior to onResume() completing"); } } // Now really resume, and install the current status bar and menu. mCalled = false; mFragments.dispatchResume(); mFragments.execPendingActions(); onPostResume(); if (!mCalled) { throw new SuperNotCalledException( "Activity " + mComponent.toShortString() + " did not call through to super.onPostResume()"); } }

16行就是打出的出錯日誌

知道為什麼出錯後解決這個問題就不難了,既然我的activity是沒有UI的,出錯的activity主題的配置如下:

<activity android:name=".DialogActivity" 
    ...
    android:theme="@android:style/Theme.NoDisplay/>

這個一個沒有UI的主題,為了解決問題,只需要將主題改成透明的即可,ps:記住透明不等於沒有UI哦,如下所示:

<activity android:name=".DialogActivity" 
    ...
    android:theme="@android:style/Theme.Translucent.NoTitleBar"/>