Skip to content

Instantly share code, notes, and snippets.

@gonjay
Last active August 29, 2015 13:57
Show Gist options
  • Save gonjay/9359598 to your computer and use it in GitHub Desktop.
Save gonjay/9359598 to your computer and use it in GitHub Desktop.
public class FaceActivity extends Activity implements Camera.FaceDetectionListener{
String TAG = this.getClass().getName();
private CameraPreview mPreview;
private Camera mCamera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_face);
if (!checkCameraHardware(this))finish();
mCamera = getCameraInstance();
if (mCamera == null)finish();
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout)findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
@Override
protected void onDestroy(){
super.onDestroy();
try {
mCamera.release();
} catch (Exception e){
}
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
@Override
public void onFaceDetection(Camera.Face[] faces, Camera camera) {
if (faces.length > 0){
Camera.Face f = faces[0];
Log.v(TAG, ("Detected" + faces.length + "faces,the ID of first face is:" + f.id ));
Log.v(TAG, "leftEye : " + f.leftEye);
Log.v(TAG, "mouth : " + f.mouth);
Log.v(TAG, "rect : " + f.rect);
Log.v(TAG, "rightEye: " + f.rightEye);
mCamera.stopFaceDetection();
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void onClick(View v){
switch (v.getId()){
case R.id.button_capture:
mCamera.setFaceDetectionListener(this);
mCamera.startFaceDetection();
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment