場景
沉浸式場景,由於劉海屏,劉海位置會對內容有遮擋,爲了讓內容展示完全,需要對劉海屏進行適配。劉海屏 寬度、高度形狀均略有差異,適配難度也比較高。
如下圖,適配即處理好Notch遮擋,與耳朵區顯示問題。
適配
android P
開始提供劉海屏相關api.針對android P
及以後的版本,可以使用android API
適配。 但有些廠商(小米,華爲等)在android P之前(android O版本)已經支持劉海屏。
需要注意的問題:
- 沉浸式需要適配。其他不需要適配。
- 劉海的高度 不超過 狀態欄的高度,可通過填充狀態欄,做簡單適配。
- 當應用不顯示 status bar 時(如全屏遊戲),不允許應用使用耳朵區,系統默認填黑。
android官方適配
android P開始支持劉海屏。
提供的常用api有:
- 獲取耳朵區域
- 獲取安全距離
//android P獲取劉海屏區域
if (Build.VERSION.SDK_INT >= 28) {
//android P以上使用google 官方判斷
View decorView = getWindow().getDecorView();
WindowInsets windowInsets = decorView.getRootWindowInsets();
if (windowInsets != null) {
DisplayCutout cutout = windowInsets.getDisplayCutout();
if (cutout != null) {
List<Rect> list = cutout.getBoundingRects();
//list rect即爲劉海區域,左上角,右下角座標
}
}
}
//android P獲取獲取劉海屏安全距離
if (Build.VERSION.SDK_INT >= 28){
View decorView = window.getDecorView();
WindowInsets windowInsets = decorView.getRootWindowInsets();
if (windowInsets != null) {
DisplayCutout cutout = windowInsets.getDisplayCutout();
if(cutout != null) {
//獲取頂部安全距離
return cutout.getSafeInsetTop();
}
}
return 0;
}
但是,其他一些操作,官方文檔中沒有,例如:關閉劉海屏。這種能力需要針對機型,對接具體廠商適配。
廠商api適配
當系統版本爲android O時,需要用廠商提供的api適配。
有些接口要用反射來做。例如小米,判斷是否爲劉海屏
/**
* 只適用於判斷MIUI 是否有劉海屏
* SystemProperties.getInt("ro.miui.notch", 0) == 1;
*
* @return true,小米手機爲劉海屏
*/
private static boolean hasMIUINotchInScreen() {
try {
Class<?> clz = Class.forName("android.os.SystemProperties");
Method get = clz.getMethod("getInt", String.class, int.class);
return (int) get.invoke(clz, "ro.miui.notch", -1) == 1;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
劉海屏關閉需要廠商提供的api
目前,小米和華爲的手機支持,關閉劉海屏,這時會在頂部劉海屏相當高度,貼一層黑條。
/**
* 劉海屏是否關閉
* @param contentResolver ContentResolver
* @return true 劉海屏關閉
*/
public static boolean isNorchClose(ContentResolver contentResolver) {
if(isMIUI()) {
return Settings.Global.getInt(contentResolver, "force_black", 0) == 1;
} else if( isHuaWei() ) {
return Settings.Secure.getInt(contentResolver,"display_notch_status", 0) == 1;
}
return false;
}