[源碼探究]Only fullscreen opaque activities can request orientation 緣由及解決方案

今天在三星S8上碰見一個奇葩問題Only fullscreen opaque activities can request orientationjava

1、出現場景

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

2、解決方案

manifest中移除android:screenOrientation="portrait"android

3、緣由(源碼中尋找)

查看Android 8.0源碼app

3.一、ActivityRecord#setRequestedOrientation

Alt text

有幾個條件:google

  • 非全屏 !fullscreen
  • targetSdkVersion的設置爲大於26 appInfo.targetSdkVersion > O
  • ActivityInfo.isFixedOrientation(requestedOrientation)

因此下邊來跟蹤一下ActivityInfo.isFixedOrientation(requestedOrientation)spa

3.二、跟蹤ActivityInfo.isFixedOrientation(requestedOrientation)

在這裏插入圖片描述

繼續跟蹤isFixedOrientationPortrait(int orientation)設計

在這裏插入圖片描述

最後的緣由找到了,就是由於orientation == SCREEN_ORIENTATION_PORTRAIT3d

3.三、總結一下

  • 若是一個 targetSdkVersion>26的Android App
  • 運行在Android 8.0(含) 以上的設備上時
  • 若是啓動的Activity爲透明Activity

screenOrientation 需爲默認狀態code

4、Google爲何這麼作?

stackoverflow 中看到一句話。cdn

這句話,我在google官方文檔上並無找到依據,但通過個人驗證是正確的blog

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。

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

綜上所述,移除android:screenOrientation="portrait" 的解決方案,徹底符合Google的設計本意,並不是Bug

相關文章
相關標籤/搜索