今天在三星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

有幾個條件:
- 非全屏
!fullscreen - targetSdkVersion的設置為大於26
appInfo.targetSdkVersion > O - ActivityInfo.isFixedOrientation(requestedOrientation)
所以下邊來跟蹤一下ActivityInfo.isFixedOrientation(requestedOrientation)
3.2、跟蹤ActivityInfo.isFixedOrientation(requestedOrientation)

繼續跟蹤isFixedOrientationPortrait(int 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 ==========

