public class MainActivity extends Activity implements SurfaceHolder.Callback, PictureCallback, OnClickListener, AutoFocusCallback {
private static final int AUTO_FOCUS = 0;
private static Camera sCamera;
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private Button mButton;
private Handler mHandler;
private boolean mIsAutoFocus;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
@SuppressWarnings("deprecation")
void init() {
mIsAutoFocus = true;
mHandler = new AutoFocusHandler();
mSurfaceView = (SurfaceView) findViewById(R.id.preview);
mButton = (Button) findViewById(R.id.capture);
mButton.setOnClickListener(this);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
sCamera = Camera.open();
try {
sCamera.setPreviewDisplay(holder);
setDisplayOrientation(sCamera, 90);
sCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
sCamera.autoFocus(this);
}
public void surfaceDestroyed(SurfaceHolder holder) {
sCamera.release();
sCamera = null;
}
protected void setDisplayOrientation(Camera camera, int angle) {
Method setOrientation;
try {
setOrientation = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
if (setOrientation != null)
setOrientation.invoke(camera, new Object[] { angle });
} catch (Exception e1) {
}
}
public void onPictureTaken(byte[] data, Camera camera) {
startActivity(data);
}
public void onClick(View v) {
mIsAutoFocus = false;
sCamera.takePicture(null, null, null, this);
}
public void onAutoFocus(boolean success, Camera camera) {
if (mIsAutoFocus) {
mHandler.sendEmptyMessageDelayed(AUTO_FOCUS, 1500);
}
}
@SuppressLint("HandlerLeak")
class AutoFocusHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case AUTO_FOCUS:
sCamera.autoFocus(MainActivity.this);
break;
default:
break;
}
}
}
代码系列2:Camera的简单应用
最新推荐文章于 2024-07-13 23:11:02 发布