SurfaceView - > Surface没有有效的本机窗口| Android Camera API | hardware.camera2

时间:2016-12-29 23:00:28

标签: java android

我在使用最新Camera API的Android开发的SurfaceView类上遇到了麻烦。我已经仔细检查过我的最低API级别是21。

我已经通过两种方式解决了这个问题,一种是在XML中创建SurfaceView,然后将其值赋予我的私有SurfaceView或使用公共构造函数创建它。

使用SurfaceView,我可以使用getHolder()获取SurfaceHolder,然后使用getSurface()获取Surface。

在我发布的代码中,我只是使用公共构造函数创建它。

此SurfaceView应该使用createCaptureSession()

放置相机的预览

这是我的代码,是我在昨天与另一个项目一起尝试后尝试的快速类实现。检查MainActivity的onCreate()和onOpened(),其中使用了SurfaceView。

package com.example.universitywork.canyouwork;
/* IMPORTS */ 

public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {
// CREAMOS CLASES
private CameraManager mManager;
private CameraDevice cDevice;
private CaptureRequest cRequest;
private Handler handle = new Handler();
private SurfaceView surface;
private SurfaceHolder holder;
private Surface under;
private final CameraDevice.StateCallback mCallbackDevice = new CameraDevice.StateCallback() {

    @Override
    public void onOpened(CameraDevice camera) {
        cDevice = camera;
        try {
            camera.createCaptureSession(Arrays.asList(under), mCallbackSession, handle);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onDisconnected(CameraDevice camera) {
        System.out.println("ONDC");
    }

    @Override
    public void onError(CameraDevice camera, int error) {
        System.out.println("ONerror");
    }
};

private final CameraCaptureSession.CaptureCallback mCaptureCallback = new CameraCaptureSession.CaptureCallback() {

};

private final CameraCaptureSession.StateCallback mCallbackSession = new CameraCaptureSession.StateCallback() {

    @Override
    public void onConfigured(CameraCaptureSession session) {
        try {
            System.out.println("LLEGO AQUI");

            cRequest = cDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW).build();
          //  session.capture(cRequest, mCaptureCallback, handle);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConfigureFailed(CameraCaptureSession session) {
        System.out.println("ONCONFIGUREFAILED");
    }
};

public MainActivity() {

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    surface= new SurfaceView(this);
    holder = surface.getHolder();
    holder.addCallback(this);
    holder.setFixedSize(500,500);
    under= holder.getSurface();
    mManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    String id = getId(mManager);
    try {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mManager.openCamera(id, mCallbackDevice, handle);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}


@Override
public void surfaceCreated(SurfaceHolder holder) {
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    System.out.println("ONCHANGED");
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    System.out.println("ONDESTROYED");
}
public String getId (CameraManager manager) {
    try {
        for (String cameraId : manager.getCameraIdList()) {
            CameraCharacteristics characteristics =         manager.getCameraCharacteristics(cameraId);
            int orientation =     characteristics.get(CameraCharacteristics.LENS_FACING);
            if (orientation == CameraCharacteristics.LENS_FACING_FRONT) return cameraId;
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
    return "NULL";
}}

快进到错误:

    E/Legacy-CameraDevice-JNI: getNativeWindow: Surface had no valid native window.
    E/Legacy-CameraDevice-JNI: LegacyCameraDevice_nativeDetectSurfaceDimens: Could not retrieve native window from surface.
    D/AndroidRuntime: Shutting down VM
    E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.universitywork.canyouwork, PID: 4885
                  java.lang.IllegalArgumentException: Surface was abandoned
                      at android.hardware.camera2.utils.SurfaceUtils.getSurfaceSize(SurfaceUtils.java:70)
                      at android.hardware.camera2.params.OutputConfiguration.<init>(OutputConfiguration.java:97)
                      at android.hardware.camera2.params.OutputConfiguration.<init>(OutputConfiguration.java:71)
                      at android.hardware.camera2.impl.CameraDeviceImpl.createCaptureSession(CameraDeviceImpl.java:474)
                      at com.example.universitywork.canyouwork.MainActivity$1.onOpened(MainActivity.java:40)
                      at android.hardware.camera2.impl.CameraDeviceImpl$1.run(CameraDeviceImpl.java:134)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                   Caused by: android.hardware.camera2.legacy.LegacyExceptionUtils$BufferQueueAbandonedException
                      at android.hardware.camera2.legacy.LegacyExceptionUtils.throwOnError(LegacyExceptionUtils.java:64)
                      at android.hardware.camera2.legacy.LegacyCameraDevice.getSurfaceSize(LegacyCameraDevice.java:540)
                      at android.hardware.camera2.utils.SurfaceUtils.getSurfaceSize(SurfaceUtils.java:68)
                      at android.hardware.camera2.params.OutputConfiguration.<init>(OutputConfiguration.java:97) 
                      at android.hardware.camera2.params.OutputConfiguration.<init>(OutputConfiguration.java:71) 
                      at android.hardware.camera2.impl.CameraDeviceImpl.createCaptureSession(CameraDeviceImpl.java:474) 
                      at com.example.universitywork.canyouwork.MainActivity$1.onOpened(MainActivity.java:40) 
                      at android.hardware.camera2.impl.CameraDeviceImpl$1.run(CameraDeviceImpl.java:134) 
                      at android.os.Handler.handleCallback(Handler.java:739) 
                      at android.os.Handler.dispatchMessage(Handler.java:95) 
                      at android.os.Looper.loop(Looper.java:148) 
                      at android.app.ActivityThread.main(ActivityThread.java:5417) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

我认为它与SurfaceView的大小或底层表面有关。也许我没有正确使用它,但Android文档说它可以使用SurfaceView。

4 个答案:

答案 0 :(得分:3)

经过几天和不眠之夜的camera2 api战斗之后,我得出的结论是文档甚至样本都不是很清晰,或者说,我的学习速度很慢。当我看到很多人都在与api进行斗争时,对我感到安慰的是,对所提出问题的答复不一定提供解决方案和简单答案。

我试图拍两张照片-一张一张接一张。即使使用finish()关闭Intent并重新打开它也没有提供解决方案-我根本无法在不重新启动整个应用程序的情况下拍摄第二张照片。在第二张图片中,API继续失败,并出现以下问题:-

Fatal Exception: java.lang.IllegalArgumentException Surface had no valid native Surface.

android.hardware.camera2.legacy.LegacyCameraDevice.nativeGetSurfaceId (LegacyCameraDevice.java)
android.hardware.camera2.legacy.LegacyCameraDevice.getSurfaceId (LegacyCameraDevice.java:658)
android.hardware.camera2.legacy.LegacyCameraDevice.containsSurfaceId (LegacyCameraDevice.java:678)

这些代码行提供了线索和我的突破:-

ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
outputSurfaces.add(reader.getSurface());
outputSurfaces.add(new Surface(textureView.getSurfaceTexture()));

我们检索位图并将其保存到文件中,如下所示:-

image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);

然后终于:-

if (image != null) {
    image.close();
}

被许多人忽视:-

ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);

由于某种原因,它仍然作为实例运行,并且将继续执行直到关闭。它不会随GC一起回收,并且在关闭类时也不会被销毁。您还应该手动关闭阅读器:-

if (image != null) {
    image.close();
}
if(reader != null) {
    reader.close();
}

它可以解决我所有的camera2问题,我确定只能等到下一次。希望这也对其他人有所帮助!

答案 1 :(得分:1)

经过几个小时后,我意识到我只需要到达SurfaceCreated()并且我没有达到它,解决方法是在onCreate()中没有openCamera。

答案 2 :(得分:1)

创建SurfaceView后,您只需调用“ openCamera”功能

将此代码放入onCreate(此代码用于kotlin)

 mySurfaceView!!.holder!!.addCallback(object: SurfaceHolder.Callback {
        override fun surfaceChanged(holder: SurfaceHolder, format: Int,
                                    width: Int, height: Int) {

        }

        override fun surfaceCreated(holder: SurfaceHolder) {

            openCamera()

        }

        override fun surfaceDestroyed(holder: SurfaceHolder) {

        }
    })

答案 3 :(得分:0)

我找到了解决方案 使用此方法选择尺寸

private static Size chooseOptimalSize(Size[] choices, int width, int height) {
        Size bigEnough = null;
        int minAreaDiff = Integer.MAX_VALUE;
        for (Size option : choices) {
            int diff = (width*height)-(option.getWidth()*option.getHeight()) ;
            if (diff >=0 && diff < minAreaDiff &&
                    option.getWidth() <= width &&
                    option.getHeight() <= height) {
                minAreaDiff = diff;
                bigEnough = option;
            }
        }
        if (bigEnough != null) {
            return bigEnough;
        } else {
            Arrays.sort(choices,new CompareSizeByArea());
            return choices[0];
        }

    }