Camera preview still black

2019-02-07 12:53发布

问题:

I'm trying the camera preview on my Android applications. When I try on my real devices, it gives me black screen.

This is my code and it doesn't throw any error, but the screen is still black. Any ideas?

import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.FrameLayout;

public class ARrazerNav extends Activity{

public void onCreate(Bundle savedInstanceState){
    try{
        super.onCreate(savedInstanceState);
        CustomCameraView cv = new CustomCameraView(this.getApplicationContext());
        FrameLayout r1 = new FrameLayout(this.getApplicationContext());
        setContentView(r1);
        r1.addView(r1);
    }catch (Exception e) {
        // TODO: handle exception
    }
}

public class CustomCameraView extends SurfaceView{
    Camera camera;
    SurfaceHolder previewHolder;
    public CustomCameraView(Context ctx){
        super(ctx);
        previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        previewHolder.addCallback(surfaceHolderListener);
    }
    SurfaceHolder.Callback surfaceHolderListener = new SurfaceHolder.Callback(){

        public void surfaceDestroyed(SurfaceHolder holder) {
            // TODO Auto-generated method stub
            camera.stopPreview();
            camera.release();
        }

        public void surfaceCreated(SurfaceHolder holder) {
            // TODO Auto-generated method stub
            camera = Camera.open();
            try{
                camera.setPreviewDisplay(previewHolder);
            }catch (Throwable th) {
                // TODO: handle exception
            }
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                int height) {
            // TODO Auto-generated method stub
            Parameters params = camera.getParameters();
            params.setPreviewSize(width, height);
            params.setPictureFormat(PixelFormat.JPEG);
            camera.setParameters(params);
            camera.startPreview();

        }
    };
}

}

Can somebody give me some sort of explanation why it gives me black screen?

回答1:

Maybe you are being affected by this bug of android Camera bug.

The workaround to which is proposed here Work around.

I hope it helps..



回答2:

Also refer this Link

You are calling the last three lines too early. You have to wait for the surface to be prepared before calling setPreviewDisplay() and you have to wait for the surface to be sized (surfaceChanged()) before calling startPreview(). This project has what you need.