Skip to content

Instantly share code, notes, and snippets.

View DavidTPate's full-sized avatar

David Pate DavidTPate

  • Denver
View GitHub Profile
<resources>
<style name="Theme.SimpleCamera" parent="@android:style/Theme.Black.NoTitleBar.Fullscreen" />
</resources>
public class SimpleCameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "Simple Camera Preview";
private final SurfaceHolder mHolder;
private final Camera mCamera;
@SuppressWarnings("deprecation")
public SimpleCameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
@SuppressWarnings("deprecation")
@Override
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
Log.d(TAG, "Preview Surface does not exist");
return;
}
@Override
protected void onResume() {
super.onResume();
initialize();
}
@Override
protected void onPause() {
super.onPause();
deinitialize();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_camera_activity);
}
private boolean hasCamera(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
// this device has a camera
Log.d(TAG, "At Least one Camera Detected!");
return true;
} else {
// no camera on this device
Log.d(TAG, "No Cameras detected.");
return false;
}
private Camera getCameraInstance() {
try {
// attempt to get a Camera instance
// this will open the default camera, which is the back-facing camera (if it exists)
mCamera = Camera.open();
// need to handle the Media Server Dying
mCamera.setErrorCallback(getErrorCallback());
Log.d(TAG, "Camera Opened Successfully");
} catch (RuntimeException e) {
private Camera.ErrorCallback getErrorCallback() {
if (mErrorCallback == null) {
mErrorCallback = new Camera.ErrorCallback() {
@Override
public void onError(int error, Camera camera) {
if (error == Camera.CAMERA_ERROR_SERVER_DIED) {
deinitialize();
initialize();
}
}