package com.yidianling.ydlcommon.custom.tool

import android.app.Activity
import android.content.pm.ActivityInfo
import android.content.res.TypedArray
import android.os.Build
import android.util.Log

/**
 * Created by haorui on 2019/6/11.
 * Des:Android系统帮助类
 */
object AndroidSystemHelper {

    /**
     * 修复Android 8.0 崩溃，Only fullscreen activities can request orientation
     */
    fun fixAndroidOrientationBug(activity: Activity) {
        if (!isAllowSetOrientation(activity)) {
            val result = resetOrientation(activity)
            Log.i(this.javaClass.simpleName, "onCreate resetOrientation when Oreo, result = " + result);
        }
    }

    /**
     * 反射调用ActivityInfo#isTranslucentOrFloating()
     * 判断当前Activity是否透明or悬浮
     */
    fun isTranslucentOrFloating(activity: Activity): Boolean {
        var isTranslucentOrFloating = false
        try {
            val styleableRes = Class.forName("com.android.internal.R\$styleable").getField("Window").get(null) as IntArray
            val ta = activity.obtainStyledAttributes(styleableRes)
            val m = ActivityInfo::class.java.getMethod("isTranslucentOrFloating", TypedArray::class.java)
            m.isAccessible = true
            isTranslucentOrFloating = m.invoke(null, ta) as Boolean
            m.isAccessible = false
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return isTranslucentOrFloating
    }

    /**
     * 重置屏幕方向
     */
    fun resetOrientation(activity: Activity): Boolean {
        try {
            //设置方向为改为SCREEN_ORIENTATION_UNSPECIFIED：未指定类型
            val field = Activity::class.java.getDeclaredField("mActivityInfo")
            field.isAccessible = true
            val o = field.get(activity) as ActivityInfo
            o.screenOrientation = -1
            field.isAccessible = false
            return true
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    /**
     * 是否允许设置屏幕方向
     */
    fun isAllowSetOrientation(activity: Activity): Boolean {
        return if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating(
                activity
            )
        ) {
            Log.i(this.javaClass.simpleName, "avoid calling setRequestedOrientation when Oreo.")
            false;
        } else {
            true
        }
    }


}
