プログラムでOSはHarmony(HarmonyOS)かAndroidか判断する方法


ファーウェイは2021年7月23日にHUAWEI MatePad 11をリリースしました。このタブレットはHarmonyOSを搭載しています。AndroidのアプリもHarmonyOSのアプリも正常動作します。

アプリの中でOSがHarmonyOSかAndroidか判断する場面があるかもしれないので、その方法を公開します。

public boolean isHarmonyOS() {
    try {
        Class classType = Class.forName("com.huawei.system.BuildEx");
        Method method = classType.getMethod("getOsBrand");
        ClassLoader classLoader = classType.getClassLoader();
        if (classLoader != null && classLoader.getParent() == null) {
            return "harmony".equals(method.invoke(classType));
        }
    } catch (ClassNotFoundException e) {
    } catch (NoSuchMethodException e) {
    } catch (Exception e) {
    }
    return false;
}