Using the Camera API

Posted on Nov 18, 2009 (4 years ago). Seen 192,981 times. 96 comments. Permalink Feed
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
Stream Posts: 42
Tagged as: Android Tutorial

Android SDK supports the connectivity to the built-in camera. Using the camera to take photos is relatively easy. It is somewhat harder to setup the camera preview to work properly.

In our main activity, we create the Preview object. This object will create the Camera object and return it to the CameraDemo activity.

Next we register couple of call-back method with the Camera to be performed when the user takes a photo.

shutterCallback is called when the shutter is opened and picture is taken. rawCallback and jpegCallback will get the data for the raw and jpeg encoding of the photo. It's up to you to do something with this data, such as save it to the SD card.

CameraDemo.java
Code:

package com.example;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;

public class CameraDemo extends Activity {
private static final String TAG = "CameraDemo";
Camera camera;
Preview preview;
Button buttonClick;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

preview = new Preview(this);
((FrameLayout) findViewById(R.id.preview)).addView(preview);

buttonClick = (Button) findViewById(R.id.buttonClick);
buttonClick.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
preview.camera.takePicture(shutterCallback, rawCallback,
jpegCallback);
}
});

Log.d(TAG, "onCreate'd");
}

ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};

/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};

/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
// write to local sandbox file system
// outStream =
// CameraDemo.this.openFileOutput(String.format("%d.jpg",
// System.currentTimeMillis()), 0);
// Or write to sdcard
outStream = new FileOutputStream(String.format(
"/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};

}

Preview class handles the preview from the camera. It subclasses SurfaceView class so that it can be placed in the UI itself. It also implements the SurfaceHolder.Callback interface so it gets the callbacks when the UI becomes available.

Preview.java
Code:

package com.example;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

class Preview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "Preview";

SurfaceHolder mHolder;
public Camera camera;

Preview(Context context) {
super(context);

// 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, acquire the camera and tell it where
// to draw.
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);

camera.setPreviewCallback(new PreviewCallback() {

public void onPreviewFrame(byte[] data, Camera arg1) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format(
"/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPreviewFrame - wrote bytes: "
+ data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Preview.this.invalidate();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}

public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
// Because the CameraDevice object is not a shared resource, it's very
// important to release it when the activity is paused.
camera.stopPreview();
camera = null;
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(w, h);
camera.setParameters(parameters);
camera.startPreview();
}

@Override
public void draw(Canvas canvas) {
super.draw(canvas);
Paint p = new Paint(Color.RED);
Log.d(TAG, "draw");
canvas.drawText("PREVIEW", canvas.getWidth() / 2,
canvas.getHeight() / 2, p);
}
}

The layout is fairly straight forward. We have the FrameLayout as the placeholder for the Preview to be attached to. This is done programmatically in CameraDemo.onCreate().

/res/layout/main.xml

Code:

<?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" android:id="@+id/layout">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Camera Demo"
android:textSize="24sp" />

<FrameLayout android:id="@+id/preview"
android:layout_weight="1" android:layout_width="fill_parent"
android:layout_height="fill_parent">
</FrameLayout>

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/buttonClick"
android:text="Click" android:layout_gravity="center"></Button>

</LinearLayout>


And finally remember to add <uses-permission android:name="android.permission.CAMERA" /> to your AndroidManifest.xml file.

The final app looks like this:




Source Code:

/static/tutorials/CameraDemo.zip

Comments

Posted on Jan 21, 2010
Photo Me Me
Me
Member since Jan 21, 2010
Thanks, that was very helpful.
It is better to call camera.release() when finishing the activity.
Posted on Feb 1, 2010
Photo Me Me
Org
Member since Feb 1, 2010
Where you save the image with FileOutputStream, I get "java.lang.IllegalArgumentException: File /sdcard/whatever.jpg contains a path separator". Any ideas?
Posted on Mar 1, 2010
Photo A Member
Org
Member since Mar 1, 2010
Thanks, I tried the code on my android phone. I am seeing a picture orientation problem. On focus I see on the phone screen a picture that is inverted. I am trying to figure why this happens. If you have an answer to this, please let me know.
Posted on Mar 5, 2010
Photo SeungHun Lee
Iconlab
Member since Mar 4, 2010
How to use OCR??
Posted on Mar 5, 2010
Photo A Member
Org
Member since Mar 1, 2010
OCR?? What does it stand for?
Posted on Apr 11, 2010
Photo Chun Ming Chin
UIUC
Member since Apr 11, 2010
This code only allows us to take a snap shot once before it freezes over. How could we make it take multiple shots and save it onto a file system or SD card?
Posted on Apr 11, 2010
Photo Chun Ming Chin
UIUC
Member since Apr 11, 2010
Optical Character Recognition
Posted on Jul 14, 2010
Photo Nan Z
GoldSequence
Member since Jul 14, 2010
First of all, it is really appreciated that you can post this sample application.

I tried to bring up this app in OS 2.2 and run in Nexus one phone. However, the app crashes and DDMS shows the following message:
ERROR/QualcommCameraHardware(59): Invalid preview size requested: 480x604


The problem can be fixed by using getOptimalPreviewSize() function and surfaceChanged() function provided in an Android sample program CameraPreview.java. It can be found at
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/CameraPreview.html (retrieved today)

However, I still observe camera orentation and image size distortion problems.
Posted on Jul 14, 2010
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
Hmm, I'll have to test this on an actual NexusOne. I do have a newer version of the code here:
https://thenewcircle.com/static/courseware/android/Camera.zip
Posted on Jul 18, 2010
Photo Luka Divac Krnic
Me
Member since Jul 18, 2010
Hello Marko. The last one Camera.zip works fine on my HTC with Android 2.1 (the last code somehow never did). There is only one peculiarity: once I activate your new Camera Demo, I can not start the Camera App of HTC Corpotion or any other App that uses the cam. When I restart the Phone, everything is again OK. Seems some resources stay allocated "forever".

Greetings, Luka
Posted on Jul 18, 2010
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
Hi Luka,

You may want to try this new and improved version of Camera app. Here is the code: https://thenewcircle.com/static/courseware/android/Camera.zip.

It is possible that in the old code camera object was not released properly so other apps weren't able to get a hold of the camera.

Cheers,
Marko
Posted on Jul 22, 2010
Photo Sai Kiran Veluri
Lead Engineer
Incube
Member since Jul 22, 2010
Hi,

i am new bee to android development, and we have a requirement that we need to take a picture, but we should not show the camera preview. Is it possible with Android camera API's?, if yes, could you please let me know, how to achieve this.

Thanks & Regards,
Sai Kiran V.
Posted on Jul 26, 2010
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
Yes, it's possible. The CameraDemo does that, ++.
Posted on Jul 30, 2010
Photo Sai Kiran Veluri
Lead Engineer
Incube
Member since Jul 22, 2010
Hi,

I have another requirement that we need to set the color effects, auto exposure, image resolution, camera frame rate, and zoom level, using Android 2.2 (Froyo). but i have not seen any sample codes which are setting these values, so could you please let me know how to achieve these things using Android SDK 2.2 version.

Thanks & Regards,
Sai Kiran V
Posted on Aug 19, 2010
Photo Kimir Mahajan
COLLEGE
Member since Aug 19, 2010
Hi,
m getting a checkered screen with a box moving around can you help me with that...!
Thanks,
Kimir
Posted on Aug 26, 2010
Photo Assaf Passal
None
Member since Aug 26, 2010
Your sample help very much,
I use nexus one with android 2.2 , and I have tow problems with the sample:
a. After I take the picture the view freeze and change only if I take a new picture or change the orientation.
b. After I close the app I can't use the camera any more

Thanks for advance,
Posted on Aug 30, 2010
Photo Uday P
Softsol
Member since Aug 30, 2010
Hi,

I have done some changes in the camera sample, so that we can use built in camera after executing this application. camera.release() is not calling in surfaceDestroyed(SurfaceHolder holder) method in preview.java.

but i can't able to resolve the freeze issue..

Can any body tell Is it possible to do the camera capture without preview??? I've written a code to capture with in the service. But it is not working properly..
The below is my code...

@Override
public void onStart(Intent intent, int startid)
{
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();

try
{
camera = Camera.open();
System.out.println("After creating the Camera Object -----------" + camera.toString());
Camera.Parameters parameters = camera.getParameters();

parameters.setFlashMode("on");
camera.setParameters(parameters);

System.out.println("Before takePicture() method ---------");
camera.takePicture(shutterCallback, null, jpegCallback);
} catch (Exception exception) {
camera.release();
camera = null;
exception.printStackTrace();
}
Log.d(TAG, "onStart");
}

Am i doing any thing wrong here???
Posted on Sep 12, 2010
Photo RedSox Robbe
N/A
Member since Sep 12, 2010
I came here in a round about way (Google search Android Flash API), but the question is somewhat relevant to the content of this post anyway...

I want to use the camera flash as a strobe (via toggle button), for a lighting effects app.
Simple toggle on, flash (pre-determined frequency), then simply toggle off.

Can anyone point me in the right direction? I don't want or need to activate camera (or do I?).

I will be targeting SDK 7+.

Thanks!

/r
Posted on Oct 20, 2010
Photo Umar Shafique
Sigmtec
Member since Oct 20, 2010
dear marko,


your have done great job its working but with few bugs

could you please tell me

1) how to change orientation of taken image automatically when phone orientation is gets changed?

2)why application shows crash after closing it.. and camera does not work


waiting for your reply


regards
Umar(mr_muskurahat@yahoo.com,mr_muskurahat@hotmail.com)
Posted on Oct 26, 2010
Photo Tonny Ta
Company
Member since Oct 26, 2010
Hi Marko,
Thanks for your code. But i have same problems as Umar Shafique when I click back. May be when call method surfaceDestroyed(). (I use HTC Hero, and HTC EVo)

Regards
Tonny
Posted on Oct 27, 2010
Photo Umar Shafique
Sigmtec
Member since Oct 20, 2010
there is not solution to change orientation :(

i have searched alot and still working will provide you solution if find something
Posted on Oct 30, 2010
Photo Ehsan ul haq
pmedia4u
Member since Oct 30, 2010
hi

i use this its working fine for me , but i have one question

How can i call camera in tabhost and take picture and send it to my mysql server through web service


thanks



Ehsan-ul-haq
Posted on Nov 24, 2010
Photo Rainer Freudiger
Private
Member since Nov 24, 2010
camera problem after closing app:

goto:


// Called when the holder is destroyed
public void surfaceDestroyed(SurfaceHolder holder) { // <14>
camera.stopPreview();

and replace:

camera.stopPreview();

with:
camera.release();
Posted on Feb 7, 2011
Photo Shabbir Anjum
RohaanTech
Member since Feb 7, 2011
I want to develop application for take picture using Mobile build-in Camera. using your Camera Demo application which mobile will best for it.
Posted on Apr 7, 2011
Photo Ramesh Mishra
Iespl
Member since Apr 7, 2011
hello everyone....
i am working on the same camera module but the thing is that i need to develop the application which will run in background, means camera should work in background and take images continuously at a regular interval of time and send the image to server.
please help me out i m not getting any help and my boss is creating problem for me...
Posted on Apr 19, 2011
Photo Bradley Andersen
pvnp llc
Member since Apr 19, 2011
Hello,

The preview class appears to work well, with one exception: I have the same problem as Umar, Tonny, and Uday:

Take a picture => App freezes unless I change orientation or re-start.

For example, I may take a landscape, then a portrait, but never two portraits consecutively or two landscapes consecutively.

Do you have a solution for this?

Thank you!
/bda
Posted on Apr 21, 2011
Photo Bradley Andersen
pvnp llc
Member since Apr 19, 2011
A hackalicious solution:
[1] close the camera, then
[2] call onCreate().

If you want to see some code, contact me.
Posted on May 1, 2011
Photo Apostolos Giokas
Education
Member since May 1, 2011
Very nice example but i had 2 problems:

a) the preview writes constantly on the sd .. i fixed this

b) after a while i the program crashes I get the following message on the Debuger:
Code:

05-01 19:38:32.315: ERROR/libgps(159): sec_gps_inject_location: not implemented.
05-01 19:38:36.865: ERROR/CameraService(13218): CameraService::connect X (pid 14438, new client 0x26838) rejected. (old pid 14438, old client 0x21df8)
05-01 19:38:36.875: WARN/dalvikvm(14438): threadid=1: thread exiting with uncaught exception (group=0x400207d8)
05-01 19:38:36.905: ERROR/AndroidRuntime(14438): FATAL EXCEPTION: main
05-01 19:38:36.905: ERROR/AndroidRuntime(14438): java.lang.RuntimeException: Fail to connect to camera service
.
.
.
Posted on May 1, 2011
Photo Paul Haverkamp
Student
Member since May 1, 2011
Thanks for this! This is the only camera tutorial I can get working, so I really appreciate it.

However, I run it, close it (and include the suggested camera.release) but the camera now is all messed up if I re-run this, or if I use the regular camera app. By all messed up I mean it looks like color static if that makes sense. Remember old old tube tvs that when you turned them on you couldn't really see things as it was going in all directions and the colors were weird (maybe I'm dating myself here) and you had to hit it to get the picture normal? Well, that is pretty much what it looks like.

Any ideas?

Also, how to get back to the camera after you sit on preview? And why do the live preview and preview look as if the screen is squished?

Thanks anyone for any help! I'm running on 2.2.1.
Posted on May 1, 2011
Photo Paul Haverkamp
Student
Member since May 1, 2011
I took the battery out and replaced it and that fixed it, but not good.

Any ideas of how to prevent this?
Posted on May 10, 2011
Photo Alba G
Eetac
Member since May 10, 2011
How I can to Remove the sound of the shutter?

Any ideas?

I know the file is camera_click.ogg
Posted on May 14, 2011
Photo Francis Fernandes
frontAvenue
Member since May 14, 2011
Hi i have implemented the example and it works fine on an emulator (By works fine i mean i see a Square blocked image and a click button which im assuming to the camera). But if i install this app on a real phone i get an error "The application has stopped unexpectedly ." I am installing it on a Android 2.2.2 LG phone. Any idea as to what wrong am i doing ?
Posted on May 17, 2011
Photo Asha Ashraf
Lrit
Member since May 17, 2011
When I click on the button ,I cannot see the image on the emulator.But it is stored in sdcard.I want to see the image on the emulator.How it is possible?And one more doubt picture sored in sd card is android icon.From where we get this to take picture of that icon?
Posted on May 17, 2011
Photo Asha Ashraf
Lrit
Member since May 17, 2011
When I click on the button ,I cannot see the image on the emulator.But it is stored in sdcard.I want to see the image on the emulator.How it is possible?And one more doubt picture sored in sd card is android icon.From where we get this to take picture of that icon?
Posted on May 25, 2011
Photo Sujit Singaraju
CTS
Member since May 25, 2011
Hi Marco,
Ur article here serves as an excellent tutorial for developing camera based applications in Android.
Here, I request you to address an issue. I have to develop zoom in and zoom out option while taking the pictures. I am new to Android and hence would like to see a sample code for enabling the Zoom in and Zoom out WHILE CAPTURING AN IMAGE.

Regards
Sujit
Posted on Jun 5, 2011
Photo THIBAULT David
Pointcube
Member since Jun 5, 2011
Do you know if it is possible to get the image frame buffer of the camera without showing preview?
Thanks.
Posted on Jun 18, 2011
Photo Sam Povilus
Povil.us
Member since Jun 18, 2011
<Sarcasam> This is an excellent tutorial.
Could you please write my final project for me?</Sarcasam>

This actually is a good tutorial.
I'm trying to get the LED that acts as a flash to turn on to use it as a flashlight. I don't care to use the image sensor at all. I upgraded this project to API 2.2 and did
Code:

camera = Camera.open();
Camera.Parameters camParam = camera.getParameters();
camParam.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(camParam);

at the beginning of surfaceCreated(). It works, but if I move the same lines to the onCreate() method in a new project and thats all the code the light no longer turns on, any ideas as to why that is?
Posted on Jun 23, 2011
Photo Alvin Rivera
None
Member since Jun 23, 2011
I already use this code but when I run it in emulator all I can see is a black and white checkered. anyone could tell me whats going on about this?
Posted on Jun 23, 2011
Photo Sam Povilus
Povil.us
Member since Jun 18, 2011
Alvin Rivera,
Does your emulator have a camera?
Posted on Jul 16, 2011
Photo Deng Changyou
Shanghai Jiaotong University
Member since Jul 16, 2011
hi? pleased to see your article?but ? you said that:"rawCallback and jpegCallback will get the data for the raw and jpeg encoding of the photo. " I get null in data[] from the rawCallback, while the data[] in jpeg is available, would you tell me why? and how can I get the raw data from this interface . thanks...
Posted on Jul 27, 2011
Photo Arthur Grant
LPS
Member since Jul 27, 2011
Hi, I got the code to work and it works just fine. My issue is that the client Im developing for is not using SD cards and so I need to save the image taken from the camera to either the res/raw folder or somewhere else... Any idea on how to make that happen? The Droid development site wasn't very helpful...
Posted on Aug 11, 2011
Photo Kavirajan Ganesan
Egrove systems
Member since Aug 11, 2011
Hi Marco
I am new to android i need your help iyour application working fine while taking picture i want MONO effect i dont know how to select colour effect so please tell me and how to convert image from jpeg to tiff format pls tell.
Posted on Aug 19, 2011
Photo Spoo D
Student
Member since Aug 19, 2011
Hi,

I see that from the above code, I can capture the image once. If I need to take picture again, then I have to start the app all over again. Is there anything that can be modified in the code such that, the image can be captured one after another (i.e., the preview is started again after capture of one image)

Thanks,
Posted on Aug 30, 2011
Photo Lev Tatarov
tel aviv uni.
Member since Aug 30, 2011
Hi Marco,
first of all - i just wanted to say thanks for all the information you put out on the web, for a beginner in Android development it was extremely helpful.

when i use this code everything works fine except one thing - the camera is inverted or rotated (when i move it up and down the picture moves sideways instead). any idea why that might be and how to resolve this?

b.t.w- i run it on a GalaxyS (Android 2.2.1)

Thanks!
Posted on Sep 15, 2011
Photo Lev Tatarov
tel aviv uni.
Member since Aug 30, 2011
i found a solution for the inversion problem:
i simply defined the activity that hosts the camera to be in "landscape" orientation in the manifest file and set the layout accordingly
Posted on Sep 19, 2011
Photo Mobarakol Islam
KUET
Member since Sep 18, 2011
I've used emulator 1.5 but when I run it in emulator all I can see is a black and white checkered. In console it shows this report:

[2011-09-19 13:47:20 - CameraDemo] ActivityManager: Can't dispatch DDM chunk 4d505251: no handler defined
Posted on Sep 19, 2011
Photo Lev Tatarov
tel aviv uni.
Member since Aug 30, 2011
i think that the checkered screen is the emulator's default camera (because it doesn't use n actual camera). best to try it out on a real phone
Posted on Sep 19, 2011
Photo Mobarakol Islam
KUET
Member since Sep 18, 2011
I'm out of real phone. I need a code with camera preview for a higher development of image based application. I really need to active webcam & take photos by emulator.
Posted on Sep 19, 2011
Photo Lev Tatarov
tel aviv uni.
Member since Aug 30, 2011
a simple google search produced these:
http://www.tomgibara.com/android/camera-source
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emulator.html
and more...
Posted on Sep 19, 2011
Photo Mobarakol Islam
KUET
Member since Sep 18, 2011
Thank You...:D
Posted on Sep 22, 2011
Photo nageswara rao Rajana
Gmantis solutions
Member since Jul 14, 2011
Hi,

I integrated this code in my application and tested on Samsung Galaxy pop and
Samsung Galaxy Fit but not working on HTC device. So tell me what might be issue.
Version are same.

The Error is: Force close Application.

Thanking you,
Nagu.
Posted on Sep 23, 2011
Photo Steve T
Nil
Member since Sep 23, 2011
I found that if I included "setDisplayOrientation (int degrees)" (in the Preview.SurfaceChanged Method) it fixed the problem with the rotation that some ppl posted about earlier.
Posted on Oct 13, 2011
Photo Ron Grant
Delta Graphics
Member since Oct 13, 2011
First many thanks to Marko for posting this example code. At this point I would be lost without it. Having problems with rapid orientation change crashing app -- (I am just using preview functionality for now). Maybe this is my cue to learn how to use the debugger.

Appears not to crash if Camera has chance to fully initialize and output a preview frame before orientation changes. Maybe this is beyond my control since Activity is destroyed and re-created on orientation change.

I did add camera.release() in surfaceDestroyed, and for fun added stopPreview() to start of surfaceChanged (just a guess on adding that)

I see that Camera documentation suggests that camera open should occur in Activity onResume(), provided that a valid surface is present, and releasing camera should be done in OnPause() to free up camera when activity is not in the foreground.

I am running the app. on a inexpensive Huawei-M835 v 2.2.2 phone with limited resources.
Posted on Oct 30, 2011
Photo Mobarakol Islam
KUET
Member since Sep 18, 2011
I got an error after running this code for Android Emulator AVD1.6 . I've connected webcam but can't preview in the emulator. The error message is:

"application messaging (in process com.android.mms) is not responding

Please need a solution.

Thanks
Posted on Nov 11, 2011
Photo Mostafa Alm
Student
Member since Nov 11, 2011
[img] http://up11.up-images.com/up/viewimages/fe8b64fdd1.jpg [/img]
[b] there is problem with me can you see this photo and pl z, help me[b]
Posted on Nov 11, 2011
Photo Gudu Chango
nose
Nada
Member since Nov 11, 2011
hi..!! how can a take more photos with the button?
Posted on Nov 12, 2011
Photo Mostafa Alm
Student
Member since Nov 11, 2011
yes I also have this problem(black,white)screen can you help me if you found seluation
Posted on Dec 4, 2011
Photo T H
P
Member since Dec 4, 2011
Regarding the freezing of the preview after accessing takePicture on Android 2.3.3:

Try adding the following to the onClick() function after the takePicture call:

((FrameLayout) findViewById(R.id.preview)).removeView(preview);
((FrameLayout) findViewById(R.id.preview)).addView(preview);
Posted on Jan 3, 2012
Photo Akash Arjunwadkar
Freelancer
Member since Jan 3, 2012
Hi dude,

I want to develop an application which captures the image on android phone and can edit the image. I used ur code and its working fine. Im new in androids can u pls help me the code .
Posted on Jan 26, 2012
Photo Mayank Sharma
Android
Member since Jan 26, 2012
Hi

i am getting this error,,,this comes when i take 2 pics concecutively.

01-26 18:30:47.878: E/AndroidRuntime(11801): java.lang.RuntimeException: takePicture failed

i use samsung captivate 2.3 gingerbread.

Best Regards
Posted on Feb 1, 2012
Photo Pavan Mahajan
Software Developer
Octagon
Member since Feb 1, 2012
Hi,
I am new in android development .
I have one application in which i have to display the images from camera continuously and above the image i have to show one crosshair line . Is it possible in android.
If yes can you please tell me how to implement that or sample code is greatly appreciated.

Thanks
Posted on Feb 9, 2012
Photo Jim Graham
me? are you kidding? :-)
Member since May 12, 2011
I just tested the demo (CameraDemo.zip) and it's definitely
got a problem. I got countless (seriously, I wasn't about to
try to count them) image files that were not viewable, and
three that were (I took three test shots). All were dated at
the same time. The non-viewable image files were about 125kB,
and the viewable 3 were about 715 kB (which seems really small
for a 5 MP image!).

Android device: Acer Iconia A500 tablet.

Oh, I did not rebuild the app. I used the included apk file.

Later,
--jim
Posted on Feb 20, 2012
Photo Chris D
Home
Member since Feb 20, 2012
Hi,

I am having some problems with the preview after a picture is taken.

I tried using the following code in the OnClick() function as mentioned above:

((FrameLayout) findViewById(R.id.preview)).removeView(preview);
((FrameLayout) findViewById(R.id.preview)).addView(preview);

The result is that the application starts as always, but when I press the button I get an error message (the application stopped unexpectedly).

Then I tried to launch it again by adding one line at a time. The removeView line seems to work fine, but when I add the addView line then I get the error message.

Could anyone please help me with it?


Thanks
Posted on Mar 6, 2012
Photo David Richards
Rails Developers
Andolasoft
Member since Mar 6, 2012
Android SDK supports the connectivity to the built-in camera. Using the camera to take photos is relatively easy. It is somewhat harder to setup the camera preview to work properly.
Posted on Mar 9, 2012
Photo J Burgess
Insertion Studios
Member since Mar 9, 2012
The Freezing preview can be overcome by implementing the "onPictureTaken" callback.

camera.takePicture(null, null, photoCallback);

PictureCallback photoCallback=new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//Perform any saving here
new SaveFile().execute(data);
camera.startPreview();
}
};
Posted on Mar 29, 2012
Photo Kenneth Besañez
none
None
Member since Mar 29, 2012
Hello!

Good day to you sir!

Do you have a code for a camera android application which has a photo search option and also can rename the file name of the photo?? I really don't know what to do about this one and I badly need your help.

Hoping for your positive reply sir!
Posted on Apr 30, 2012
Photo Amit Suri
Android Developer
IT Sector
Member since Apr 30, 2012
Hi Marko Gargenta,

I am able to capture image but at the same time i want to send that captured image to server, Please Help me

Thanks
Amit
Posted on May 19, 2012
Photo Mohammed Abdulwahed
Programmer
MOI-IQ
Member since May 19, 2012
very cool
Posted on Jun 4, 2012
Photo Sujewan Vijayakumar
isoft infosys
Member since Jun 4, 2012
Hai Sir,

I am used Android 4.0 AVD (Android Virtual Device). In that AVD have a default camera application. It's show the live camera view... But your application displaying Black and White boxes....
any solutions???
Posted on Jun 5, 2012
Photo Werner Weiler
Nothing
Member since Jun 5, 2012
After the hint of David Richards I can save more than one picture and the app didn't crash. But my problem is, that the preview still remains visible. Also the setting of the PreviewSize in surfaceChanged shows no reaction. The preview seems to be the topmost layer and the other elements like buttons and the background image is visible, too but the preview seems to be over them.

I'm trying it on a tablet with WM8650_Android2.2_1.2.2_20110409
May it be that it doesn't work with this version?

That's my main.xml:

Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:background="@drawable/metal_back1"
android:orientation="vertical" >

<AbsoluteLayout
android:id="@+id/absoluteLayout1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:background="@drawable/metal_back1" >

<FrameLayout
android:id="@+id/preview"
android:layout_width="1dp"
android:layout_height="1dp"
android:visibility="visible"
>

</FrameLayout>

<Button
android:id="@+id/buttonClick1"
android:layout_width="81dp"
android:layout_height="41dp"
android:layout_weight="0.73"
android:text="Click" />

<ImageButton
android:id="@+id/buttonClick"
android:layout_x="9dp"
android:layout_y="151dp"
android:background="@android:color/transparent"
android:src="@drawable/btnblue250" />
</AbsoluteLayout>
</LinearLayout>



Any ideas what I'm doing wrong?

Regards,
Werner
Posted on Jul 10, 2012
Photo Mahe Pra
ABC
Member since Jul 10, 2012
I have tried your code. It works perfectly. I am trying to automatically turn on the camera and take a video clip. That means if the accelerometer reading > 1.5 (Gforce>1.5) automatically turn on the camera. Is that possible?
Posted on Jul 30, 2012
Photo Moez Rebai
Ensi
Member since Jul 30, 2012
hi ,
i wanna know if u could store u picture in database or server coz i need that code im my summer project
Posted on Jul 30, 2012
Photo Moez Rebai
Ensi
Member since Jul 30, 2012
hi iwanna know if u can resolve the problem od storing images taken constantisouily on server
Posted on Jul 30, 2012
Photo Aiah Tudio
Programmer
Bodapps.com
Member since Jul 30, 2012
hi! i am new in making android apps, i tried doing your code and it works perfectly. but i can't seem to save the images that i captured. a little help maybe?thanks!
Posted on Aug 8, 2012
Photo Mahe Pra
ABC
Member since Jul 10, 2012
@ Moez Rebai I wanna store the picture in the SD card.. Still I couldn't do that.. Did you solve your problem. I have the problem in automatically turn on the camera when the force > 2.0
I have written a method to calculate the force.. That works fine..
Posted on Aug 13, 2012
Photo Wei Ho
Personal
Member since Aug 13, 2012
Hi,I`m very new in Android develop .I got a question that I compiled this with Android version 2.3.3 on Eclipse with no errors, but when I tried to use this example with my Nexus S with Android 4.1.1 then I can`t even open this project , is there something wrong with my phone?or other problems? thanks!!
Posted on Aug 13, 2012
Photo Wei Ho
Personal
Member since Aug 13, 2012
Hi, I tried LG-E720 with Android 2.2 this time, but still, after i installed this application,when I tried to open it, it would automatically shut down no matter which phone i tested, I`ve tested on Android 2.2 , 2.3.7, 4.1.1 , can anyone explain to me what is this happening? i`m very new to android, thanks!!!
Posted on Aug 21, 2012
Photo Tu?n Anh Hoàng
Hj
Ad
Member since Aug 21, 2012
Thank for topic, Now I want to use Camera font-facing....
when I use"camera = Camera.open();
Parameters parameters = camera.getParameters();
parameters.set("camera-id", 2);
camera .setParameters(parameters);"

open camera font-facing. I don't save picture on sdcard...

Everybody help me.......
Posted on Sep 7, 2012
Photo Wei Ho
Personal
Member since Aug 13, 2012
i`m also try to use front-facing cam right now, but i caught up with some problem that i don`t know why, below is my code(I`ve found them in some other webs):

public void surfaceCreated(SurfaceHolder holder) {
Camera.CameraInfo caminfo = new Camera.CameraInfo();
for ( int camIdx = 0; camIdx < Camera.getNumberOfCameras(); camIdx++ ) {
Camera.getCameraInfo( camIdx, caminfo );
if ( caminfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ) {
try {
camera = Camera.open( camIdx );
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}

...........

i always got NullPointException, can anyone please tell me why? i`m using android 2.3.3
Posted on Sep 7, 2012
Photo Wei Ho
Personal
Member since Aug 13, 2012
i tried your solution to front facing cam, but i tested on my 2.3.7 phone it was still facing rear, can you tell me why, please?
Posted on Dec 11, 2012
Photo Shivani Kumar
jr. s/w devlopr
Sudesi
Member since Dec 11, 2012
the camera opens in an inverted manner....how do i change the orientation of the camera???
and i want the image to be directly attached to the email on confirmation from the user..how do i go abt it??? wer shud i make the changes in my code??? Please help its really urgent!!!!!!!!!!!
Posted on Dec 17, 2012
Photo Pankaj Sp
Android
SP
Member since Dec 17, 2012
Hi Marko
can Camera start on service??
Because when application forcefuly on sleep mode then it will not capature image so if you can help to run camera on service.
Thanks..
Posted on Mar 27, 2013
Photo Pete Aloha
Petealoha
Member since Mar 27, 2013
Hi Marko,

The CAMERADEMO app works only when the PREVIEW is not active. If I add "camera.startPreview()" after outStream.close(), the PREVIEW becomes active after JPEG capture but the app acts funny.

outStream = new FileOutputStream(String.format(
"/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
camera.startPreview();


Sometimes it hangs and sometimes it crashes on restart and refuses to restart again. I am not sure if it is a problem with the app not releasing the camera resources and left the camera at a hung state when the app exists (by hitting the BACK or ESCAPE button). How can I tell the app to release the camera when the app exits while allowing the camera preview to stay active? Thanks.

Pete
Posted on Mar 27, 2013
Photo Pete Aloha
Petealoha
Member since Mar 27, 2013
Marko,

Somehow I was able to fix the app crash on exit or app unable to restart error by adding "camera.stopPreview()"

in the surfaceChanged method. Can anyone explain why?


// Called when the holder is destroyed
public void surfaceDestroyed(SurfaceHolder holder) {
camera.release();
camera = null;
}

// Called when holder has changed
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
camera.stopPreview(); //added to fix app exit/restart error
camera.startPreview();
}

Also, I commented out this line because it doesn't seem to do anything.

public void onPreviewFrame(byte[] data, Camera camera) {
//Preview.this.invalidate(); //doesn't affect app
}


Pete
Posted on Mar 30, 2013
Photo Pete Aloha
Petealoha
Member since Mar 27, 2013
Hi Marko,

Initially, your code captured all the video data and saved them as raw data in the SD card. In the newer version, you removed the raw data saving feature. The camera preview remains active when the raw data is saved. And we ended up with a ton of raw files and not knowing what to do with them. But when JPEG file is requested when we click the take picture button, the camera preview is stopped. I added a code in the SURFACECHANGED function to restart the PREVIEW after the JPEG image is saved. Can someone explain why saving raw file doesn't stop the camera preview but saving JPEG file stops the preview? Also can I use the raw file to feed to FACE DETECTION and how do I do it?


Pete
Posted on Apr 2, 2013
Photo Rad Remo
Home
Member since Apr 2, 2013
Hello Marko,

I have been working on the app for quite some time. Now there is a necessity that I also get a thumbnail of the image taken immediately along with the original image. I need this because I need to post the thumb nail onto a webpage as soon as the pic was taken. Can you tell me how can i do that?
Posted on Apr 2, 2013
Photo Pete Aloha
Petealoha
Member since Mar 27, 2013
Rad,

I don't think it allows you to do both in one shot because full size capture is taken as soon as you started the capture action and the image buffer is cleared automatically after the captured image is exported to a file so the thumbnail image is cleared. You can get the thumbnail only if you don't initiate an image export. But when you initiates the thumbnail export in post-capture the image buffer is also reset automatically clearing the full image. So I don't know if there is another way to get both. But you can snap the full size and then down size the captured image to any other size but it takes extra processing on your part.

Pete
Posted on Apr 3, 2013
Photo Rad Remo
Home
Member since Apr 2, 2013
Thank you so much for the information. I was trying to get that done wasn't sure what to do. Any how I did make another external code to the the task taught I could do it with in the app. Any ways thanks for the info.
Posted on Apr 3, 2013
Photo Pete Aloha
Petealoha
Member since Mar 27, 2013
Rad,

I found another useful link. The author thinks its a Nexus/Samsung problem.

http://kevinpotgieter.wordpress.com/2011/03/30/null-intent-passed-back-on-samsung-galaxy-tab/

Pete
Posted on Apr 4, 2013
Photo Rad Remo
Home
Member since Apr 2, 2013
Thanks for the info Pete, Ill surely try that one out soon.
Posted on Apr 13, 2013
Photo Ieltxu Ispizua Madariaga
Deusto
Member since Apr 13, 2013
Hi!,

I have to take picture automatically when spent 2 seconds and take that picture to convert it into a bitmap and passed to another class to analize if the eyes are closed or no, so I used a TIMER calling pictureTaken.

Yesterday, I realized that you cannot modify the mobile camera application to take picture automatically without button. But we can construct our own camera with PictureCallback class to do it automatically with a TIMER.

My dude is how to change the camera rotation 90 grades because is always -90 grades changes.

And another dude is that how I can passed the photo taken into the byte[] data that we define in the public void onPictureTaken(byte[] data, Camera camera) { } .

Finally, as I said, I want to convert the data information of the byte, into a bitmap and then insert into another class to analyze the eyes.

Sincerely,

my email is: ieltxu_90@hotmail.com THANKS!!
Posted on Jun 18, 2013
Photo Shubham Patni
S F
Member since Sep 12, 2011
Hello,

Is there any way to start/stop camera preview using third app for any existing running app.
Posted on Jul 28, 2013
Photo Arron Lee
Dt
Member since Jun 26, 2013
Hi, Kavirajan Ganesan.
Have you ever tried a 3rd party tool to help you convert image from jpeg to tiff format? I know how to do it on PC. It saves me a lot of time. But I'm not so familiar with the related app on the phone. I hope you success. Good luck.
Posted on Jul 29, 2013
Photo Ewf Hrfhyre
Reyret
Member since Jul 29, 2013
hi, i know a software you can use to convert jpeg to tiff vb.net.but i am not certain it can be used on the phone as well. it is powerful when the app used on the pc. you can give it a try.
Posted on Nov 27, 2013
Photo Aswathy Nair
Engineer Trainee
IB Tech
Member since Nov 27, 2013
HI Marko

I tried you first version of code as am not able see your newer versions and when i tried in a tab, "Unfortunately the camera is stopped" is viewed. PLease can you tell me why dis is happening.
Posted on Jan 30, 2014
Photo Jake Garbo
android programmer
Eglobio
Member since Jan 30, 2014
thanks for this camera demo ..
but i cannot download the file in this link please re upload.
https://thenewcircle.com/static/courseware/android/Camera.zip
it will help alot thank You every much .. :)