天天看點

一文分析 Only fullscreen opaque activities can request orientation 報錯原因及解決方案

今天在三星S8上遇見一個奇葩問題

Only fullscreen opaque activities can request orientation

一、出現場景

  • 三星手機S8 android 8.0
  • targetSdkVersion 27
  • 透明Activity

二、解決方案

manifest中移除

android:screenOrientation="portrait"

三、原因(源碼中尋找)

檢視Android 8.0源碼

3.1、ActivityRecord#setRequestedOrientation

一文分析 Only fullscreen opaque activities can request orientation 報錯原因及解決方案

有幾個條件:

  • 非全屏

    !fullscreen

  • targetSdkVersion的設定為大于26

    appInfo.targetSdkVersion > O

  • ActivityInfo.isFixedOrientation(requestedOrientation)

是以下邊來跟蹤一下

ActivityInfo.isFixedOrientation(requestedOrientation)

3.2、跟蹤ActivityInfo.isFixedOrientation(requestedOrientation)

一文分析 Only fullscreen opaque activities can request orientation 報錯原因及解決方案

繼續跟蹤

isFixedOrientationPortrait(int orientation)

一文分析 Only fullscreen opaque activities can request orientation 報錯原因及解決方案

最後的原因找到了,就是因為

orientation == SCREEN_ORIENTATION_PORTRAIT

3.3、總結一下

  • 如果一個

    targetSdkVersion>26

    的Android App
  • 運作在

    Android 8.0(含) 以上

    的裝置上時
  • 如果啟動的Activity為

    透明Activity

screenOrientation 需為預設狀态

四、Google為什麼這麼做?

stackoverflow

中看到一句話。

這句話,

我在google官方文檔上并沒有找到依據,但經過我的驗證是正确的

If you use a fullscreen transparent activity, there is no need to specify the orientation lock on the activity. It will take the configuration settings of the parent activity. So if the parent activity has in the manifest:

這種情況下,

透明Activity使用的是棧中,上一層可見Activity的orientation設定

。仔細想一想是合理的,是以這并不是一個bug。

五、最後重申一遍解決方案

綜上所述,移除

android:screenOrientation="portrait"

的解決方案,完全符合Google的設計本意,并非Bug

= THE END =

文章首發于公衆号”CODING技術小館“,如果文章對您有幫助,可關注我的公衆号。

繼續閱讀