制作相机,首先需要添加照相的权限。添加方法是在AndroidManifest.xml文件中添加
<uses-permission android:name=” android.permission.CAMERA”>
注意这里是uses不是user否则会报错链接无法连接camera的错误
其次:修改布局文件:如下代码所示。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <SurfaceView android:id = "@+id/mySurfaceView" android:layout_width="320px" android:layout_height="240px"> </SurfaceView> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" > <Button android:id="@+id/myButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="打开"/> <Button android:id="@+id/myButton2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="关闭"/> </LinearLayout> </LinearLayout>
package tcamera.n.com.tcamera; import android.app.Activity; import android.hardware.Camera; import android.hardware.Camera.ErrorCallback; import java.io.IOException; import android.os.Bundle; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceHolder.Callback; import android.view.SurfaceView; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity implements Callback { Camera myCamera; SurfaceView mySurfaceView; SurfaceHolder mySurfaceHolder; Button myButton1; Button myButton2; boolean isPreview = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tcam); mySurfaceView = (SurfaceView) findViewById(R.id.mySurfaceView); myButton1 = (Button) findViewById(R.id.myButton); myButton2 = (Button) findViewById(R.id.myButton2); mySurfaceHolder = mySurfaceView.getHolder(); mySurfaceHolder.addCallback(this); mySurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); myButton1.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { initCamera(); } }); myButton2.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { if (myCamera != null & isPreview) { myCamera.stopPreview(); myCamera.release(); myCamera = null; isPreview = false; } } }); } public void initCamera() { if (!isPreview) { myCamera = Camera.open(0); } if (myCamera != null & !isPreview) { try { myCamera.setPreviewDisplay(mySurfaceHolder); myCamera.startPreview(); } catch (IOException e) { e.printStackTrace(); } isPreview = true; } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceCreated(SurfaceHolder holder) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { } }
如果在模拟器中运行,可以得到如图所示的情形。如果在真机上运行,则会打开摄像头,将实际的影响显现出来。关闭时,则定在关闭时的画面。这样基本可以完成了图像的采集。如果程序中对相机有要求的话,可以采用这种方式进行