Skip to content

Instantly share code, notes, and snippets.

@Jayatubi
Created May 24, 2018 05:18
Show Gist options
  • Save Jayatubi/8a1a56fd94310fd5ec24f5e3e88728eb to your computer and use it in GitHub Desktop.
Save Jayatubi/8a1a56fd94310fd5ec24f5e3e88728eb to your computer and use it in GitHub Desktop.
Detect notch on Android devices for Huawei, Oppo, Vivo
package com.actgames.fci.util;
import android.app.Activity;
import com.unity3d.player.UnityPlayer;
import java.lang.reflect.Method;
/**
* Created by mofei on 2018/5/11.
*/
public class NotchUtil {
public static int hasDeviceNotch() {
// Use oppo official API to detect notch
// Ref https://open.oppomobile.com/service/message/detail?id=61876
if (hasSystemFeature("com.oppo.feature.screen.heteromorphism")) {
return 0;
}
if (hasNotchInHuawei()) {
return getWidthInHuawei();
}
if (hasNotchInVivo()) {
return 0;
}
return -1;
}
static int getWidthInHuawei() {
int[] ret = new int[]{0, 0};
try {
final Activity activity = UnityPlayer.currentActivity;
if (activity == null) return 0;
ClassLoader cl = activity.getClassLoader();
Class HwNotchSizeUtil = cl.loadClass("com.huawei.android.util.HwNotchSizeUtil");
Method get = HwNotchSizeUtil.getMethod("getNotchSize");
ret = (int[]) get.invoke(HwNotchSizeUtil);
return ret[1]; // [0]值为刘海宽度int;[1]值为刘海高度
} catch (Exception e) {
//ignored
}
return 0;
}
static boolean hasSystemFeature(String feature) {
final Activity activity = UnityPlayer.currentActivity;
try {
if (activity != null) {
return activity.getPackageManager().hasSystemFeature(feature);
}
} catch (Exception e) {
//ignored
}
return false;
}
/**
* Only work in Huawei devices.
*
* @return True if there is notch
*/
static boolean hasNotchInHuawei() {
boolean hasNotch = false;
try {
final Activity activity = UnityPlayer.currentActivity;
if (activity == null) return false;
ClassLoader cl = activity.getClassLoader();
Class HwNotchSizeUtil = cl.loadClass("com.huawei.android.util.HwNotchSizeUtil");
Method get = HwNotchSizeUtil.getMethod("hasNotchInScreen");
hasNotch = (boolean) get.invoke(HwNotchSizeUtil);
} catch (Exception e) {
//ignored
}
return hasNotch;
}
/**
* Only work in the latest Vivo devices
* Ref: https://dev.vivo.com.cn/doc/document/info?id=103
*
* @return True if there is notch
*/
static boolean hasNotchInVivo() {
boolean hasNotch = false;
try {
final Activity activity = UnityPlayer.currentActivity;
if (activity == null) return false;
ClassLoader cl = activity.getClassLoader();
Class FtFeature = cl.loadClass("android.util.FtFeature");
Method get = FtFeature.getMethod("isFeatureSupport", int.class);
hasNotch = (boolean) get.invoke(FtFeature, 0x00000020);
} catch (Exception e) {
//ignored
}
return hasNotch;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment