Android 12上无法调用setDisplaySurface

app_process在使用反射的方法调用setDisplaySurface方法时,对于新的手机会出问题。

使用的时候,机型是小米12,当时以为是miui13的问题,因为其余的华为、蓝厂和绿厂都运行的问题不大。

具体代码选用github上的scrcpy作为示例:

 public static void setDisplaySurface(IBinder displayToken, Surface surface) {
        try {
            CLASS.getMethod("setDisplaySurface", IBinder.class, Surface.class).invoke(null, displayToken, surface);
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }

这一段运行失败,由于使用的是反射调用所以无法获取到错误堆栈。

实际上的原因在于在Android12中,shell的权限无法去捕获"protected"的屏幕内容了,因此如果要处理这个问题的话,在创建display的时候就需要进行判断,如果Android版本大于12就只能创建非secure的Display,具体代码如下(继续以Scrcpy的代码为例)。如果因为SDK版本过低无法识别出Build.VERSION_CODES.R的话,也可以直接小于等于30.

private static IBinder createDisplay() {
        // Since Android 12, secure displays could not be created with shell permissions anymore
        boolean secure = Build.VERSION.SDK_INT <= Build.VERSION_CODES.R;
        return SurfaceControl.createDisplay("scrcpy", secure);
    }

你可能感兴趣的:(scrcpy,ADB系列,android)