bytedance / memory-leak-detector

Other
1.09k stars 178 forks source link

请教一下案例中的代码是如何调用的? #28

Closed hebangwen closed 2 years ago

hebangwen commented 2 years ago

我按照案例中的代码实现了一遍,放到我的代码里是这样子的:

protected final CameraCaptureSession.CaptureCallback  captureCallback = new CameraCaptureSession.CaptureCallback() {
    @Override
    public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
        CameraActivity.recycle(result);
    }
};

static Field sTargetField;
static Method sTargetMethod;

@SuppressLint("SoonBlockedPrivateApi")
static void recycle(TotalCaptureResult tcr) {
    try {
        if (sTargetMethod == null || sTargetField == null) {
            Method forName = Class.class.getDeclaredMethod("forName", String.class);
            Method getDeclaredMethod = Class.class.getDeclaredMethod("getDeclaredMethod", String.class, Class[].class);
            Class<?> vmRuntimeClass = (Class<?>) forName.invoke(null, "dalvik.system.VMRuntime");
            Method getRuntime = (Method) getDeclaredMethod.invoke(vmRuntimeClass, "getRuntime", null);
            Method setHiddenApiExemptions = (Method) getDeclaredMethod.invoke(vmRuntimeClass, "setHiddenApiExemptions", new Class[]{String[].class});
            Object sVmRuntime = getRuntime.invoke(null);
            setHiddenApiExemptions.invoke(sVmRuntime, new Object[]{new String[]{"L"}});
        }

        if (sTargetField == null) {
            sTargetField = tcr.getClass().getSuperclass().getDeclaredField("mResults");
            sTargetField.setAccessible(true);
        }

        if (sTargetMethod == null) {
            sTargetMethod = Class.forName("android.hardware.camera2.impl.CameraMetadataNative").getDeclaredMethod("close");
            sTargetMethod.setAccessible(true);
        }

        sTargetMethod.invoke(sTargetField.get(tcr));
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}

请问是这样调用的吗?

hebangwen commented 2 years ago

我在单摄像头上测试过了,native内存的确不会再增加了。所以这样调用是没错的。