应用程序启动时打开相机

时间:2017-02-03 05:44:46

标签: android android-camera

我正在创建一个应用程序,在应用程序启动时打开相机作为背景,类似于Snapchat。我目前使用的代码已弃用其中的部分,我不知道如何修复它们。任何帮助表示赞赏。我的代码如下。

public class CameraView extends SurfaceView implements SurfaceHolder.Callback {

private SurfaceHolder mHolder;
private Camera mCamera;

public CameraView(Context context, Camera camera) {

    super(context);
    mCamera = camera;
    mCamera.setDisplayOrientation(90);
    //get the holder and set this class as the callback, so we can get camera data here
    mHolder = getHolder();
    mHolder.addCallback(this);
    mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
}

public CameraView(Launcher launcher, android.hardware.Camera mCamera) {
    super(launcher, (AttributeSet) mCamera);
}

@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
    try{
        //when the surface is created, we can set the camera to draw images in this surfaceholder
        mCamera.setPreviewDisplay(surfaceHolder);
        mCamera.startPreview();
    } catch (IOException e) {
        Log.d("ERROR", "Camera error on surfaceCreated " + e.getMessage());
    }
}

@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
    //before changing the application orientation, you need to stop the preview, rotate and then start it again
    if(mHolder.getSurface() == null)//check if the surface is ready to receive camera data
        return;

    try{
        mCamera.stopPreview();
    } catch (Exception e){
        //this will happen when you are trying the camera if it's not running
    }

    //now, recreate the camera preview
    try{
        mCamera.setPreviewDisplay(mHolder);
        mCamera.startPreview();
    } catch (IOException e) {
        Log.d("ERROR", "Camera error on surfaceChanged " + e.getMessage());
    }
}

@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
    mCamera.stopPreview();
    mCamera.release();
}

问题是这些行已被弃用。

mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
mCamera.stopPreview();
mCamera.release();

我的Xml在下面。

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/camera_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>

</FrameLayout>

1 个答案:

答案 0 :(得分:0)

您的项目设置或导入有问题 - 旧的相机API已被弃用,但这并不妨碍它以任何方式使用。

如果您的代码段全部代码,则至少缺少包导入。如果没有,请发布您收到的实际错误消息。

Android Studio可能会发出警告,但就是这样,如果一切都设置正确的话。