Android Call Local Camera

Links to the original text: https://my.oschina.net/u/860952/blog/549212

To make an application, you may sometimes need to call a local camera, so here's how you want to call it.

Camera preview needs to add surfaceview to the layout file. Here we need to pay attention to it. In fact, FrameLayout can also be used. You can refer to it.

http://www.cnblogs.com/over140/archive/2011/11/16/2251344.html

 

1, layout

<SurfaceView 
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:id="@+id/surfaceview"/>

Just add this to the layout file.

 

2. Camera Preview

public class MainActivity extends Activity implements SurfaceHolder.Callback

Inheriting Activity and implementing SurfaceHolder.Callback, MainActivity requires us to copy the following methods:

@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		System.out.println("surfacechanged");
	}

 

@Override
	public void surfaceCreated(SurfaceHolder holder) {
		System.out.println("surfacecreated");
		//Get the camera object
		camera = Camera.open();
		try {
			//Setting up preview monitor
			camera.setPreviewDisplay(holder);
			Camera.Parameters parameters = camera.getParameters();
			
			if (this.getResources().getConfiguration().orientation 
						!= Configuration.ORIENTATION_LANDSCAPE) {
				parameters.set("orientation", "portrait");
				camera.setDisplayOrientation(90);
				parameters.setRotation(90);
			} else {
				parameters.set("orientation", "landscape");
				camera.setDisplayOrientation(0);
				parameters.setRotation(0);
			}
			camera.setParameters(parameters);
			//Start Camera Preview
			camera.startPreview();
			System.out.println("camera.startpreview");
			
		} catch (IOException e) {
			e.printStackTrace();
			camera.release();
			System.out.println("camera.release");
		}
	}

 

@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		System.out.println("surfaceDestroyed");
		if (camera != null) {
			camera.stopPreview();
			camera.release();			
		}
	}


Of course, there is the onCreate method.

@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		context = this;
		
		surfaceview = (SurfaceView)findViewById(R.id.surfaceview);
		surfaceholder = surfaceview.getHolder();
		surfaceholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		surfaceholder.addCallback(SafeActivity.this);
	}

,

Of course, some variables need to be defined.

private static Context context = null;
	private SurfaceView surfaceview;
	private SurfaceHolder surfaceholder;
	private Camera camera = null;



 

Reproduced in: https://my.oschina.net/u/860952/blog/549212

Tags: SurfaceView Android

Posted on Wed, 09 Oct 2019 13:45:07 -0400 by Cereals