Fix: Only fullscreen activities can request orientation

September 27, 2019

根据运行系统版本号重写 Activity.setRequestedOrientation(Int)。当版本号为 Android O 时不调用父类方法,避免父类检测条件并抛出异常。

1
2
3
4
override fun setRequestedOrientation(requestedOrientation: Int) {
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) return
    super.setRequestedOrientation(requestedOrientation)
}

根据文章 Only fullscreen opaque activities can request orientation 编写过滤条件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private fun isTranslucentOrFloating(): Boolean {
    var result = false
    try {
        val r = Class.forName("com.android.internal.R\$styleable")
            .getField("Window").get(null) as IntArray
        val ta = obtainStyledAttributes(r)
        val m = ActivityInfo::class.java
            .getMethod("isTranslucentOrFloating", TypedArray::class.java)
        m.isAccessible = true
        result = m.invoke(null, ta) as Boolean
        m.isAccessible = false
    } catch (ignore: Exception) {
    }
    return result
}