如何编写简单的相机应用程序?

时间:2018-01-04 16:04:08

标签: java android camera

所以,我试图根据本指南使用android.hardware.Camera API在Android上编写一个简单的相机应用程序:https://developer.android.com/guide/topics/media/camera.html

到目前为止我所做的只是创建CameraPreview类并尝试在我的主要活动中启动预览,但是当我尝试在手机上运行应用程序时它就崩溃了。我做错了什么? :(

编辑: 所以,据我所知,问题是,我的getCameraInstance()方法返回一个null对象,正如你在下面发布的Errorlog中看到的那样,因为Camera.open()失败了。但为什么会失败呢?

您可以在我的github上找到完整的源代码:https://github.com/Wursteintopf/Simple-Camera-Test

我的主要活动:

package com.example.simplecameratest;

import android.hardware.Camera;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.FrameLayout;

public class MainActivity extends AppCompatActivity {

private Camera mCamera;
private CameraPreview mPreview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mCamera = getCameraInstance();

    mPreview = new CameraPreview(this, mCamera);
    FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
    preview.addView(mPreview);
}


//Method to create a Camera Instance
public static Camera getCameraInstance(){
    Camera c = null;
    try {
        c = Camera.open();
    }
    catch (Exception e) {
        //blabla Camera not avaiable
    }
    return c;
}
}

我的CameraPreview.java:

package com.example.simplecameratest;

import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

import static android.content.ContentValues.TAG;

/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder mHolder;
    private Camera mCamera;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        mCamera = camera;

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the Camera preview in your activity.
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // set preview size and make any resize, rotate or
        // reformatting changes here

        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }
}

编辑: 这是我手机上的错误日志:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera.setPreviewDisplay(android.view.SurfaceHolder)' on a null object reference
    at com.example.simplecameratest.CameraPreview.surfaceCreated(CameraPreview.java:37)
    at android.view.SurfaceView.updateWindow(SurfaceView.java:597)
    at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:179)
    at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:944)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2082)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1134)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6050)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:860)
    at android.view.Choreographer.doCallbacks(Choreographer.java:672)
    at android.view.Choreographer.doFrame(Choreographer.java:608)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:846)
    at android.os.Handler.handleCallback(Handler.java:742)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:5527)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)

1 个答案:

答案 0 :(得分:1)

检查相机权限,如果这导致崩溃:

ActivityCompat.requestPermissions(activity,new String [] {Manifest.permission.CAMERA},requestCode);

More informations about requesting permissions on runtime