I have this activity (MakePhotoActivity) class that takes photo when you open the application. I have set it to use front facing camera.
Then I have another class, which is a SMS broadcast receiver that is already working.
Now, I would like to make it such that on receiving sms, I want it to take photo using the current class I have. But how can I integrate them together?
As I have tried copying the methods (surfaceChanged, etc) to my broadcast receiver class, and on sms receive, I placed the code that is inside the onCreate (in MakePhotoActivity). And it is not working.
public class MakePhotoActivity extends Activity implements SurfaceHolder.Callback
{
//a variable to store a reference to the Image View at the main.xml file
private ImageView iv_image;
//a variable to store a reference to the Surface View at the main.xml file
private SurfaceView sv;
//a bitmap to display the captured image
private Bitmap bmp;
private int cameraId = 0;
//Camera variables
//a surface holder
private SurfaceHolder sHolder;
//a variable to control the camera
private Camera mCamera;
//the camera parameters
private Parameters parameters;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get the Image View at the main.xml file
iv_image = (ImageView) findViewById(R.id.imageView);
//get the Surface View at the main.xml file
sv = (SurfaceView) findViewById(R.id.surfaceView);
//Get a surface
sHolder = sv.getHolder();
//add the callback interface methods defined below as the Surface View callbacks
sHolder.addCallback(this);
//tells Android that this surface will have its data constantly replaced
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
Log.d("A", "Camera found");
cameraId = i;
break;
}
}
return cameraId;
}
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
//get camera parameters
parameters = mCamera.getParameters();
//set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
//sets what code should be executed after the picture is taken
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
//decode the data obtained by the camera into a Bitmap
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
//set the iv_image
iv_image.setImageBitmap(bmp);
FileOutputStream outStream = null;
try{
outStream = new FileOutputStream("/sdcard/Image"+System.currentTimeMillis()+".jpg");
outStream.write(data);
outStream.close();
} catch (FileNotFoundException e){
Log.d("CAMERA", e.getMessage());
} catch (IOException e){
Log.d("CAMERA", e.getMessage());
}
}
};
mCamera.takePicture(null, null, mCall);
}
public void surfaceCreated(SurfaceHolder holder)
{
// The Surface has been created, acquire the camera and tell it where
// to draw the preview.
if (mCamera == null) {
cameraId = findFrontFacingCamera();
mCamera = Camera.open(cameraId);
try {
mCamera.setPreviewDisplay(holder);
// TODO test how much setPreviewCallbackWithBuffer is faster
// mCamera.setPreviewCallback((PreviewCallback) this);
} catch (IOException e) {
mCamera.release();
mCamera = null;
}
}
}
public void surfaceDestroyed(SurfaceHolder holder)
{
if (mCamera != null) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mCamera!=null)
{
mCamera.stopPreview();
mCamera.release();
mCamera=null;
}
}
}
UPDATE: This is what I have done. Put into a service, but I get an error that says app passed NULL surface, Camera server died!, ICamera died, Error 100.
I reference the code from http://easyandroidtutorials.blogspot.in/2012/09/capture-image-without-preview-as.html and made some minor changes, still can't work.
public class CameraService extends Service
{
//Camera variables
//a surface holder
private SurfaceHolder sHolder;
//a variable to control the camera
private Camera mCamera;
//the camera parameters
private Parameters parameters;
SurfaceView sv;
private int cameraId = 0;
/** Called when the activity is first created. */
#Override
public void onCreate()
{
super.onCreate();
Log.i("Service", "Service started");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
if (mCamera == null) {
cameraId = findFrontFacingCamera();
mCamera = Camera.open(cameraId);
try {
// Thread.sleep(3000);
sv = new SurfaceView(getApplicationContext());
mCamera.setPreviewDisplay(sv.getHolder());
parameters = mCamera.getParameters();
//set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
} catch (IOException e) {
// TODO Auto-generated catch block
mCamera.release();
mCamera = null;
e.printStackTrace();
}
//Get a surface
//sHolder = sv.getHolder();
//tells Android that this surface will have its data constantly replaced
// sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
} catch (Exception e) {
e.printStackTrace();
}
return Service.START_STICKY;
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
Log.d("A", "Camera found");
cameraId = i;
break;
}
}
return cameraId;
}
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
//decode the data obtained by the camera into a Bitmap
FileOutputStream outStream = null;
try{
outStream = new FileOutputStream("/sdcard/Image.jpg");
outStream.write(data);
outStream.close();
} catch (FileNotFoundException e){
Log.d("CAMERA", e.getMessage());
} catch (IOException e){
Log.d("CAMERA", e.getMessage());
}
}
};
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
Anyone with any help on this? Thanks.
in the onReceive method of your sms broadcast reciever do this:
Intent intent = new Intent(this, MakePhotoActivity.class);
startActivity(intent);
check http://developer.android.com/training/basics/firstapp/starting-activity.html for more info on starting an activities
to take the picture in the service would require you to create a dummy surfaceview. Here's a link that should explain how to do it:
how to take camera capture without a preview from a service or thread?
if you want to disable the shutter sound:
camera.enableShutterSound(false);
http://developer.android.com/reference/android/hardware/Camera.html#enableShutterSound(boolean)
Related
I copied the code Google example in:
https://developer.android.com/guide/topics/media/camera.html
For the first time I open the Camera, face detection works correctly and the callback is fired, I take the photo, close the camera, open the camera again but this time the face detection callback is not called.
If I'll restart my app, the same thing will happen - face detection will only work for the first time I'll use the camera.
here is my code:
private PictureTakenListener mPictureTakenListener;
AlertDialog mAlertDialog;
private Camera mCamera;
boolean mFaceDetectionAvailable;
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
showText("took a photo with a size of " + data.length);
releaseCamera();
if (mAlertDialog != null) mAlertDialog.dismiss();
mPictureTakenListener.photoTaken(data);
}
};
public class MyFaceDetectionListener implements Camera.FaceDetectionListener {
#Override
public void onFaceDetection(Camera.Face[] faces, Camera camera) {
if (faces != null)
if (faces.length > 0)
if (faces[0].score >= 40)
if (!takingPhotoFlag.get()){
takingPhotoFlag.set(true);
mCamera.takePicture(null, null, mPicture);
}
}
}
private void takePicture(PictureTakenListener listener){
mPictureTakenListener = listener;
if (this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
showText("this device has a camera");
showText("device has " + String.valueOf(Camera.getNumberOfCameras()) + " cameras");
int foundCamera = -1;
for (int i = 0; i < Camera.getNumberOfCameras(); i++){
Camera.CameraInfo info = new Camera.CameraInfo(); ;
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT){
foundCamera = i;
break;
}
}
if (foundCamera == -1){
return;
}
mCamera = null;
try {
mCamera = Camera.open(foundCamera); // attempt to get a Camera instance
}
catch (Exception e){
e.printStackTrace();
showText("could not open the front camera. " + e.getMessage());
return;
}
showText("successfully opened the camera");
mCamera.setDisplayOrientation(90);
Camera.Parameters params = mCamera.getParameters();
params.setPreviewSize(640, 480);
params.setRotation(270);
params.setPictureSize(640, 480);
mFaceDetectionAvailable = params.getMaxNumDetectedFaces() > 0;
mCamera.setParameters(params);
FrameLayout frameLayout = new FrameLayout(this);
if (!mFaceDetectionAvailable) {
frameLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
}
AlertDialog.Builder alert = new AlertDialog.Builder(this);
if (!mFaceDetectionAvailable)
alert.setTitle("CLICK IMAGE TO CAPTURE");
alert.setView(frameLayout).setCancelable(true).setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
releaseCamera();
runOnUiThread(new Runnable() {
#Override
public void run() {
//do UI stuff...
}
});
}
});
mAlertDialog = alert.create();
mAlertDialog.show();
mAlertDialog.getCurrentFocus();
mAlertDialog.getWindow().setLayout(960, 1280); //Controlling width and height.
mAlertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
CameraPreview mPreview = new CameraPreview(this, mCamera);
frameLayout.addView(mPreview);
} else {
showText("no camera on this device");
}
}
public interface PictureTakenListener{
void photoTaken(byte[] image);
}
/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
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
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
if (mFaceDetectionAvailable) {
mCamera.startFaceDetection();
mCamera.setFaceDetectionListener(new MyFaceDetectionListener());
}
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
private void releaseCamera(){
if (mCamera != null){
mCamera.setPreviewCallback(null);
mCamera.setFaceDetectionListener(null);
mCamera.stopFaceDetection();
mCamera.setErrorCallback(null);
mCamera.release();
mCamera = null;
showText("released camera");
}
}
Thank you.
My application freezes when I call switchCam method in my code.something must be wrong there, but i cant understand what is the problem.Can someone help me out there what is the actual problem in my code.
public class MainActivity extends AppCompatActivity {
private Camera mCamera = null;
SurfaceHolder surfaceHolder=null;
private CameraView mCameraView = null;
int currentCameraId = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);//int flag, int mask
openCam();
//setCameraDisplayOrientation(MainActivity.this, currentCameraId, mCamera);
}
public void openCam() {
try {
mCamera = Camera.open();//you can use open(int) to use different cameras
} catch (Exception e) {
Log.d("ERROR", "Failed to get camera: " + e.getMessage());
mCamera = Camera.open();//you can use open(int) to use different cameras
}
if (mCamera != null) {
mCameraView = new CameraView(this, mCamera);//create a SurfaceView to show camera data
FrameLayout camera_view = (FrameLayout) findViewById(R.id.camera_preview);
camera_view.addView(mCameraView);//add the SurfaceView to the layout
}
}
public void switchCam(View view){
int camNum = 0;
camNum = Camera.getNumberOfCameras();
int camBackId = Camera.CameraInfo.CAMERA_FACING_BACK;
int camFrontId = Camera.CameraInfo.CAMERA_FACING_FRONT;
Toast.makeText(getApplicationContext(),"Hi Cam"+camNum,Toast.LENGTH_SHORT).show();
Camera.CameraInfo currentCamInfo = new Camera.CameraInfo();
//if camera is running
if (mCamera != null){
//and there is more than one camera
mCamera.stopPreview();
mCamera.release();
//swap the id of the camera to be used
if(currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
}
else {
currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
}
mCamera = Camera.open(currentCameraId);
//setCameraDisplayOrientation(MainActivity.this, currentCameraId, mCamera);
try {
mCamera.setPreviewDisplay(surfaceHolder);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
}
CameraView class is here
public class CameraView extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mHolder;
private Camera mCamera;
int currentCameraId=0;
public CameraView(Context context, Camera camera) {
super(context);
mCamera = camera;
//get the holder and set this class as the callback, so we can get camera data here
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
}catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceCreated " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
mCamera.startPreview();
if(mHolder.getSurface() == null)//check if the surface is ready to receive camera data
return;
try{
mCamera.stopPreview();
} catch (Exception e){
//this will happen when you are trying the camera if it's not running
}
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceChanged " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
}
}
It will be my very pleasure if you share any link with me that can help me out for taking picture too .Thanks in advance :)
This question already has answers here:
How do I open the "front camera" on the Android platform?
(10 answers)
Closed 5 years ago.
i need Some Help help I am Working With An app which Can take picture automatic On Activity With Main Camera But I want to use Front Camera Instead Of Main Camera
can U Please Tell Me How To use Front Camera
here Is My Code
public class TakePicture extends Activity implements SurfaceHolder.Callback
{
//a variable to store a reference to the Image View at the main.xml file
private ImageView iv_image;
//a variable to store a reference to the Surface View at the main.xml file
private SurfaceView sv;
//a bitmap to display the captured image
private Bitmap bmp;
//Camera variables
//a surface holder
private SurfaceHolder sHolder;
//a variable to control the camera
private Camera mCamera;
//the camera parameters
private Parameters parameters;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get the Image View at the main.xml file
iv_image = (ImageView) findViewById(R.id.imageView);
//get the Surface View at the main.xml file
sv = (SurfaceView) findViewById(R.id.surfaceView);
//Get a surface
sHolder = sv.getHolder();
//add the callback interface methods defined below as the Surface View callbacks
sHolder.addCallback(this);
//tells Android that this surface will have its data constantly replaced
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
//get camera parameters
parameters = mCamera.getParameters();
//set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
//sets what code should be executed after the picture is taken
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
#Override
public void onPictureTaken(byte[] data, Camera camera)
{
//decode the data obtained by the camera into a Bitmap
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
//set the iv_image
iv_image.setImageBitmap(bmp);
TakePicture t=new TakePicture();
t.SaveBitmap(bmp);
// SendEmail(bmp);
}
};
mCamera.takePicture(null, null, mCall);
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
// The Surface has been created, acquire the camera and tell it where
// to draw the preview.
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
//stop the preview
mCamera.stopPreview();
//release the camera
mCamera.release();
//unbind the camera from this object
mCamera = null;
}
public void openFrontFacingCamera() {
numberOfCamera = Camera.getNumberOfCameras();
if(camId == Camera.CameraInfo.CAMERA_FACING_BACK){
camId = Camera.CameraInfo.CAMERA_FACING_FRONT;
Toast.makeText(getApplicationContext(), "BACK TO FRONT" ,
1000).show();
try {
camera.release();
camera = Camera.open(camId);
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (RuntimeException e) {
} catch (IOException e) {}
}else if(camId == Camera.CameraInfo.CAMERA_FACING_FRONT){
camId = Camera.CameraInfo.CAMERA_FACING_BACK;
Toast.makeText(getApplicationContext(), "FRONT TO BACK" ,
1000).show();
try {
camera.release();
camera = Camera.open(camId);
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (RuntimeException e) {
} catch (IOException e) {}
}
}
hope this function will help u
change
mCamera = Camera.open();
to
mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
I am developing this app which requires access to the camera. I have accessed it well. But there are two issues.
The preview is all stretched when the phone is vertical. Secondly, the camera preview isn't visible when I resume the app. The camera.open() function does opens the camera but I am not able to see the preview. I have tried all the help available on the forum but nothing is actually solving my problem.
-Thanks in advance!
//Camera Activity file
#SuppressLint("SimpleDateFormat")
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private FrameLayout preview;
private Button bCapture;
private Button bGallery;
private static final String TAG = "CameraActivity";
private static final int PICK_IMAGE_REQUEST = 1;
private TextView tvCheck;
public final static String EXTRA_MESSAGE = "com.epfl.mycamera.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera);
if (checkCameraHardware(getBaseContext())){
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera, CameraActivity.this);
preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
//Adding Camera Button
bCapture = (Button) findViewById(R.id.bCapture);
//Button Listener for storing images
bCapture.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, null, jpegCallback);
mCamera.startPreview();
Log.d(TAG, "takePicture");
}
});
//Adding Gallery Button
bGallery = (Button) findViewById (R.id.bGallery);
bGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvCheck = (TextView) findViewById (R.id.tvCheck);
selectImageFromGallery();
}
});
}
Log.d(TAG, "OnCreate");
}
/******************************************************************/
public void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int aRequestCode, int aResultCode, Intent aData) {
switch (aRequestCode) {
case PICK_IMAGE_REQUEST:
handleImage(aData);
break;
default:
tvCheck.setText("You can only select images.");
break;
}
super.onActivityResult(aRequestCode, aResultCode, aData);
}
private void handleImage(Intent aData) {
if ((aData != null) && (aData.getData() != null)) {
Uri selectedImage = aData.getData();
String[] filePathColumn = {MediaColumns.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
Log.d("ImageActivity", "After extracting file Path");
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Log.d("ImageActivity", "After closing the cursor");
setContentView(R.layout.activity_image_old); //setting the view to the image
ImageView imgView = (ImageView) findViewById(R.id.ivGallery);
imgView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Button bLiveCamera = (Button) findViewById(R.id.bCameraPreview);
bLiveCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.activity_camera);
mCamera.startPreview();
}
});
}
else {
tvCheck.setText("You did not select an image");
}
}
/****************************************************************/
/** Stores jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
try {
File mediaStorageDir = new File(Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCamera");
// Saving image to the SD CARD with a file operation
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator +"IMG_"+ timeStamp + ".jpg");
FileOutputStream outStream = new FileOutputStream(mediaFile);
outStream.write(data);
outStream.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
} Log.d(TAG, "onPictureTaken - jpeg");
}
};
/***************************************************************/
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
Log.d(TAG, "Camera Available");
return true;
} else {
Log.d(TAG, "No Camera Found");
return false;
}
}
/** A safe way to get an instance of the Camera object. */
public Camera getCameraInstance(){
Camera c = null;
try {
int i = Camera.getNumberOfCameras();
releaseCamera(); //in case camera is being accessed by any other app.
Log.d(TAG, "Number of Cameras "+i +"\n");
c = Camera.open(); // attempt to get a Camera instance
Log.d(TAG, "Camera Opened");
}
catch (Exception e){
Log.d(TAG, "Camera Can't Be Accessed");
}
return c; // returns null if camera is unavailable
}
#Override
protected void onPause() {
super.onPause();
releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera(){
if (mCamera != null){
mPreview.getHolder().removeCallback(mPreview);
mCamera.release(); // release the camera for other applications
}
}
#Override
public void onResume() {
super.onResume();
// Get the Camera instance as the activity achieves full user focus
if (mCamera == null) {
getCameraInstance();
mCamera.startPreview();
}
}
}
this is my camera preview class:
#SuppressLint({ "ViewConstructor", "SdCardPath" })
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "CameraPreview";
private SurfaceHolder mHolder;
private Camera mCamera;
private Size mPreviewSize;
// private Activity CameraActivity;
#SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera, Activity activity) {
super(context);
mCamera = camera;
//CameraActivity = activity;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
//add camera preview call back here.
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
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
return;
}
// stop preview before making changes
try{
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
Camera.Parameters parameters = mCamera.getParameters();
List<Size> localSizes = mCamera.getParameters().getSupportedPreviewSizes();
mPreviewSize = localSizes.get(0);
Log.d(TAG, "Width " + mPreviewSize.width);
Log.d(TAG, "Height " + mPreviewSize.height);
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height );
mHolder.setFixedSize(mPreviewSize.width, mPreviewSize.height);
requestLayout();
mCamera.setParameters(parameters);
//start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.setDisplayOrientation(90);
//setCameraDisplayOrientation(CameraActivity, 0, mCamera);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
You create a CameraPreview only onCreate() of your Activity. But the camera instance is released onPause(), and a new one is opened onResume(). Therefore, you need to set the surface again.
I am trying to use the front camera to record. My code is working fine
with the back camera.
The problem is in getFrontCameraId() and getCameraInstance()
Here is my code..
public class AndroidVideoCapture extends Activity{
private Camera myCamera;
private MyCameraSurfaceView myCameraSurfaceView;
private MediaRecorder mediaRecorder;
Button myButton;
SurfaceHolder surfaceHolder;
boolean recording;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recording = false;
setContentView(R.layout.activity_android_video_capture);
//Get Camera for preview
myCamera = getCameraInstance();
if(myCamera == null){
Toast.makeText(AndroidVideoCapture.this,
"Fail to get Camera",
Toast.LENGTH_LONG).show();
}
myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview);
myCameraPreview.addView(myCameraSurfaceView);
myButton = (Button)findViewById(R.id.mybutton);
myButton.setOnClickListener(myButtonOnClickListener);
}
Button.OnClickListener myButtonOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(recording){
// stop recording and release camera
mediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
//Exit after saved
finish();
}else{
//Release Camera before MediaRecorder start
releaseCamera();
if(!prepareMediaRecorder()){
Toast.makeText(AndroidVideoCapture.this,
"Fail in prepareMediaRecorder()!\n - Ended -",
Toast.LENGTH_LONG).show();
finish();
}
mediaRecorder.start();
recording = true;
myButton.setText("STOP");
}
}};
public int getFrontCameraId() {
CameraInfo ci = new CameraInfo();
for (int i = 0 ; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_FRONT) return i;
}
return -1; // No front-facing camera found
}
private Camera getCameraInstance(){
// TODO Auto-generated method stub
Camera c = null;
try {
int index = getFrontCameraId();
if (index == -1)
c = Camera.open(index);
// 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
}
private boolean prepareMediaRecorder(){
myCamera = getCameraInstance();
mediaRecorder = new MediaRecorder();
myCamera.unlock();
mediaRecorder.setCamera(myCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mediaRecorder.setOutputFile("/sdcard/myvideo.mp4");
mediaRecorder.setMaxDuration(60000); // Set max duration 60 sec.
mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M
mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
return false;
}
return true;
}
#Override
protected void onPause() {
super.onPause();
releaseMediaRecorder(); // if you are using MediaRecorder, release it first
releaseCamera(); // release the camera immediately on pause event
}
private void releaseMediaRecorder(){
if (mediaRecorder != null) {
mediaRecorder.reset(); // clear recorder configuration
mediaRecorder.release(); // release the recorder object
mediaRecorder = null;
myCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
if (myCamera != null){
myCamera.release(); // release the camera for other applications
myCamera = null;
}
}
public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mHolder;
private Camera mCamera;
public MyCameraSurfaceView(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int weight,
int height) {
// 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
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// make any resize, rotate or reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
}
You have a wrong condition in your module
private Camera getCameraInstance() {
// TODO Auto-generated method stub
Camera c = null;
try {
int index = getFrontCameraId();
if (index == -1)
c = Camera.open(index);
// 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
}
It should be
private Camera getCameraInstance() {
// TODO Auto-generated method stub
Camera c = null;
try {
int index = getFrontCameraId();
if (index != -1)
c = Camera.open(index);
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}