Camera.takePicture() gives no callback - android

SOLVED, SEE COMMENT ---
I never get a callback from Camera.takePicture(), I see that in logcat.
What is missing? How do I make takePicture()... take a picture?!
Most of this is directly from Android developers camera guide. I want to take pictures programmatically without any preview or user action. Using the built in camera app works fine. SDK 16.
And in the manifest I do have added:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"
android:required="true" />
The code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bTake = (Button)findViewById(R.id.b_take);
boolean boo = safeCameraOpen(camId);
Camera.Parameters parameters = mCamera.getParameters();
mCamera.setParameters(parameters);
bTake.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCamera.takePicture(shutter, null, null, picture);
Log.e(getString(R.string.app_name), "After takePicture");
}
});
}// END onCreate
/* Camera operations */
private ShutterCallback shutter = new ShutterCallback() {
#Override
public void onShutter() {
Log.e(getString(R.string.app_name), "onShutter");
}
};
private PictureCallback picture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
Log.e(getString(R.string.app_name), "onPicTaken");
}
};
/* Starting up and closing down*/
private boolean safeCameraOpen(int id) {
boolean qOpened = false;
try {
releaseCamera();
mCamera = Camera.open(id);
qOpened = (mCamera != null);
} catch (Exception e) {
Log.e(getString(R.string.app_name), "failed to open Camera");
e.printStackTrace();
}
return qOpened;
}
private void releaseCamera() {
if (mCamera != null) {
((Camera) mCamera).release();
mCamera = null;
Log.e(getString(R.string.app_name), "cam released");
}
}}

Try:
mCamera.takePicture(shutter, picture, picture);

Related

How can i enable my Camera to take picture programatically in android?

I do not want my app to call native Camera app. All I want is to enable my app to take pics programatically when the app starts without any user interaction or involvement.
Here is my code:
public class CameraActivity extends Activity implements SurfaceHolder.Callback{
Camera camera;
PictureCallback rawCallback;
ShutterCallback shutterCallback;
PictureCallback jpegCallback;
ImageView view;
boolean inPreview = false;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (ImageView)findViewById(R.id.pic);
Log.e("Camera Status: ",String.valueOf(checkCameraHardware(getApplicationContext())));
Log.e("Number Of Cameras: ",String.valueOf(Camera.getNumberOfCameras()));
start_camera();
captureImage();
rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d("Log", "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.i("Log", "onShutter'd");
}
};
jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//Set the Image to ImageView
Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(data, 0, data.length);
//view.setImageBitmap(bitmapPicture);
//Save the Image to SD Card
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format(
"/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d("Log", "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d("Log", "onPictureTaken - jpeg");
/**
* The two lines below are used to refresh the Surface View
* It works quickly then the general refresh by Default
**/
stop_camera();
start_camera();
}
};
//start_camera();
}
/** 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;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
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
}
private void start_camera()
{
try{
camera = Camera.open();
Log.e("Camera Open Status: ", "Camera opened successfully");
}catch(RuntimeException e){
Log.e("Camera Initialization:", "init_camera: " + e);
return;
}
Camera.Parameters param;
param = camera.getParameters();
//modify parameter
param.setPreviewFrameRate(20);
param.setPreviewSize(176, 144);
camera.setParameters(param);
try {
//camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
//camera.takePicture(shutter, raw, jpeg)
} catch (Exception e) {
Log.e("Camera Initialization:", "init_camera: " + e);
return;
}
inPreview=true;
}
private void captureImage() {
// TODO Auto-generated method stub
AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mgr.setStreamMute(AudioManager.STREAM_SYSTEM, true);
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
Log.e("Picture Status: ","picture taken successfully");
final Handler handler = new Handler();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mgr.setStreamMute(AudioManager.STREAM_SYSTEM, false);
}
});
}
}, 1000);
}
private void stop_camera()
{
camera.stopPreview();
camera.release();
inPreview = false;
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
}
Download the project form here
Copy the CameraLibrary into your workspace
Add these to your manifest
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="10" />
<uses-features android:name="android.hardware.camera"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<activity android:name="com.girish.cameraLibrary.CameraClass"></activity>
Now in your activity implement the com.girish.cameraLibrary.OnPictureTaken interface and Override the pictureTaken(Bitmap bitmap, File file) method which provides your with the bitmap and File
Now Create and instance of the CustomCamera
private CustomCamera mCustomCamera;
mCustomCamera = new CustomCamera(MainActivity.this);
mCustomCamera.setPictureTakenListner(this);
//To start the custom back camera use this
mCustomCamera.startCamera();
//To send an intent to applications who are listening to Camera request
mCustomCamera.sendCameraIntent();
//To start the front camera use this
mCustomCamera.startCameraFront();
The now you can access the image using pictureTaken(Bitmap bitmap, File file) method, so just use
imageview.setImageBitmap(bitmap);
EDIT
Suppose your main class is called MainActivity the write like this
public class MainActivity extends Activity implements OnPictureTaken {
.....
.....
.....
#Override
protected void onCreate(Bundle savedInstanceState) {
.....
.....
.....
//This is where you get the picture
#Override
public void pictureTaken(Bitmap bitmap, File file) {
imgCapture.setImageBitmap(bitmap);
txtPath.setText(file.getAbsolutePath());
}
Check the sample file as mentioned here

Camera Preview not visible after App Resumes

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.

Android: Taking pictures programmatically is not working

I do not have much experience with the Camera functionality in Android. I need to take a photo through code which I am planning to send back to a server. I based my logic off of this post and it works well as long as I do not add mCamera.takePicture(null, null, mPictureCallback); to the end of the surfaceChange method (which is what I want I guess). When I do add that line, it works sometimes but most of the times, I just get back a black screen. This is the main problem. I don't think there is a compatibility issue with the device because I got this functionality working atleast 3-4 times earlier.
My device that I am testing on is Galaxy Nexus
public class CameraView extends Activity implements SurfaceHolder.Callback, OnClickListener
{
private static final String TAG = "CameraTest";
Camera mCamera;
boolean mPreviewRunning = false;
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
Log.e(TAG, "onCreate");
getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera_view);
mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
mSurfaceView.setOnClickListener(this);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
}
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
if (data != null)
{
//Intent mIntent = new Intent();
//mIntent.putExtra("image",imageData);
mCamera.stopPreview();
mPreviewRunning = false;
mCamera.release();
try
{
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bitmap= BitmapFactory.decodeByteArray(data, 0, data.length,opts);
bitmap = Bitmap.createScaledBitmap(bitmap, 480, 480, false);
CameraProjectActivity.image.setImageBitmap(bitmap);
}
catch(Exception e)
{
e.printStackTrace();
}
//StoreByteImage(mContext, imageData, 50,"ImageName");
//setResult(FOTO_MODE, mIntent);
setResult(585);
finish();
}
}
};
protected void onResume()
{
Log.e(TAG, "onResume");
super.onResume();
}
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
}
protected void onStop()
{
Log.e(TAG, "onStop");
super.onStop();
}
public void surfaceCreated(SurfaceHolder holder)
{
Log.e(TAG, "surfaceCreated");
mCamera = Camera.open();
mCamera.setDisplayOrientation(90);
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
Log.e(TAG, "surfaceChanged");
// XXX stopPreview() will crash if preview is not running
if (mPreviewRunning)
{
mCamera.stopPreview();
}
Camera.Parameters p = mCamera.getParameters();
List<Camera.Size> previewSizes = p.getSupportedPreviewSizes();
Camera.Size previewSize = previewSizes.get(3);
p.setPreviewSize(previewSize.width, previewSize.height);
mCamera.setParameters(p);
try
{
mCamera.setPreviewDisplay(holder);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();
mPreviewRunning = true;
// THIS IS THE CODE THAT BREAKS IT. IS THERE ANY OTHER WAY TO DO THIS??? ********
// mCamera.takePicture(null, null, mPictureCallback);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e(TAG, "surfaceDestroyed");
// mCamera.stopPreview();
// mPreviewRunning = false;
// mCamera.release();
}
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mCamera.takePicture(null, mPictureCallback, mPictureCallback);
}
}
Any help would be appreciated.
Thanks!
I am not sure if this is a good solution, but I just fixed it by making the surfaceChanged() method synchronized and making the thread wait for a second just before I call takePicture.
try {
this.wait(1000);
mCamera.takePicture(null, null, mPictureCallback);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I believe that it is recommended to call startPreview() before setPreviewDisplay(), but this should not make a major difference.
What you see is that it takes time for the camera to initialize, and it cannot take a picture until it's ready. It's better to use a callback from camera to decide that it's ready, than to wait for arbitrary 1000 ms.
The callback you can use is a Camera.PreviewCallback. You can implement it in your CameraView class. To trigger the callback, simply add setOneShotPreviewCallback(this) to CameraView.surfaceChanged():
mCamera.startPreview();
mCamera.setPreviewDisplay(holder);
mCamera.setOneShotPreviewCallback(this);

getting null pointer exception on camera set parameters

I'm getting an error of a NullPointerException and it is referencing the line Camera.Parameters:
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int w,
int h) {
// TODO Auto-generated method stub
Log.e(TAG, "surfaceChanged");
if (mPreviewRunning) {
mCamera.stopPreview();
mPreviewRunning = false;
Log.e(TAG, "stopPeview");
}
Camera.Parameters p = mCamera.getParameters();
Log.e(TAG, "paarameters");
p.setPreviewSize(w, h);
mCamera.setParameters(p);
Log.e(TAG, " set parameters");
try {
mCamera.setPreviewDisplay(holder);
Log.e(TAG, "setPreview");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();
mPreviewRunning = true;
}
Could anyone tell me what the error is in the above code.
I will have to test it again to get the log, but here is the entire code. I did alter the manifest.
public class Picture extends Activity implements SurfaceHolder.Callback{
private String TAG;
private LayoutInflater mInflater = null;
private Camera mCamera;
boolean mPreviewRunning = false;
private SurfaceHolder mSurfaceHolder;
private SurfaceView mSurfaceView;
Button takepicture;
byte[] tempdata;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.camera_surface);
mCamera = getCameraInstance ();
mSurfaceView = (SurfaceView)findViewById(R.id.surface_camera);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mInflater = LayoutInflater.from(this);
View overView = mInflater.inflate(R.layout.cameraoverlay, null);
this.addContentView(overView, new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
takepicture = (Button) findViewById(R.id.button);
takepicture.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
mCamera.takePicture(shutterCallback, mPictureCallback,
jpegCallback);
}
});
}
private Camera getCameraInstance() {
// TODO Auto-generated method stub
Camera mCamera = null;
try {
mCamera = Camera.open();
} catch (Exception e) {
}
return mCamera;
}
ShutterCallback shutterCallback = new ShutterCallback() {
#Override
public void onShutter() {}
};
PictureCallback mPictureCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera c) {}
};
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera c) {
if(data != null) {
tempdata=data;
done();
}
}
};
void done(){
Bitmap bm = BitmapFactory.decodeByteArray(tempdata, 0, tempdata.length);
String url = Images.Media.insertImage(getContentResolver(),
bm, null, null);
bm.recycle();
Bundle bundle = new Bundle();
if(url!=null) {
bundle.putString("url", url);
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
} else {
Toast.makeText(this, "Picture can not be saved",
Toast.LENGTH_SHORT).show();
}
finish();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int w,
int h) {
// TODO Auto-generated method stub
Log.e(TAG, "surfaceChanged");
if (mPreviewRunning) {
mCamera.stopPreview();
mPreviewRunning = false;
Log.e(TAG, "stopPeview");
}
Camera.Parameters p = mCamera.getParameters();
Log.e(TAG, "paarameters");
p.setPreviewSize(w, h);
mCamera.setParameters(p);
Log.e(TAG, " set parameters");
try {
mCamera.setPreviewDisplay(holder);
Log.e(TAG, "setPreview");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();
mPreviewRunning = true;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.e(TAG, "surfaceCreated");
try {
mCamera = Camera.open();
Log.e(TAG, "camera open");
} catch(Exception e) {}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e(TAG, "surfaceDestroyed");
mCamera.stopPreview();
mPreviewRunning = false;
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
Also, the line the log referenced was the line: Camera.Parameters p = mCamera.getParameters();
Looks like mCamera is null... did you initialize it? (mCamera = Camera.open();)
See the docs for a checklist as it pertains to taking pictures
Add the below three lines in manifeast file::
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
To take pictures with this class, use the following steps:
1) Obtain an instance of Camera from open(int).
2) Get existing (default) settings with getParameters().
3) If necessary, modify the returned Camera.Parameters object and call
setParameters(Camera.Parameters).
4) If desired, call setDisplayOrientation(int).
5) Important: Pass a fully initialized SurfaceHolder to setPreviewDisplay(SurfaceHolder). Without a surface, the camera will be unable to start the preview.
6) Important: Call startPreview() to start updating the preview surface. Preview must be started before you can take a picture.
7) When you want, call takePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback) to capture a photo. Wait for the callbacks to provide the actual image data.
8) After taking a picture, preview display will have stopped. To take more photos, call startPreview() again first.
9) Call stopPreview() to stop updating the preview surface.
10) Important: Call release() to release the camera for use by other applications. Applications should release the camera immediately in onPause() (and re-open() it in onResume()).
There are many solutions, but this is an easy, dead cheap option that worked for me:
try{
mCamera.autoFocus(autoFocusCB); //Or whatever part of code that crashes
}
catch(Exception e){
Log.v("joshtag","THIS PHONE DOES NOT SUPPORT AUTOFOCUS!!"); //a warning, popup, whatever
}
VoilĂ ! Trap deactivated.
Of course, dont forget the manifest permissions....

How to use the camera Flash light as torch?

The following is my code to enable Flashlight in Android. In a Toast message it returned the following parameters: auto, on, off, torch. After setting the parameters to FLASH_MODE_TORCH, the torch is not enabling for me. My Manifest permissions are:
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<permission android:name="android.permission.FLASHLIGHT"
android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
android:protectionLevel="normal"/>
<uses-feature android:name="android.hardware.camera"></uses-feature>
My Code:
public class CameraFlashActivity extends Activity {
/** Called when the activity is first created. */
public Camera mCamera;
Parameters cameraParameters;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
boolean cameraPresnt = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if( cameraPresnt == true)
{
Toast.makeText(getApplicationContext(),"Flash is there",10).show();
if(mCamera==null)
{
try {
mCamera = Camera.open();
mCamera.startPreview();
Toast.makeText(getApplicationContext(),"Camera is present",10).show();
} catch (Exception e) {
Log.i("CameraFlashActivity", "Camera.open() failed: " + e.getMessage());
}
if(mCamera==null)
{
Toast.makeText(getApplicationContext(),"Camera object is null",10).show();
}
else
{
cameraParameters = mCamera.getParameters();
if(cameraParameters==null)
{
Toast.makeText(getApplicationContext(),"No camera parameters",10).show();
}
else
{
List<String> flashmodes = cameraParameters.getSupportedFlashModes();
String supportedFlashModes = cameraParameters.getFlashMode();
Toast.makeText(getApplicationContext(),flashmodes.toString(),10).show();
Toast.makeText(getApplicationContext(),supportedFlashModes,10).show();
cameraParameters.setFlashMode(Parameters.FLASH_MODE_ON);
mCamera.setParameters(cameraParameters);
String supportFlashModes = cameraParameters.getFlashMode();
Toast.makeText(getApplicationContext(),supportFlashModes,10).show();
Toast.makeText(getApplicationContext(),"Camera parameters are set on flash light",10).show();
}
}
}
else
{
}
}
else
{
Toast.makeText(getApplicationContext(),"Flash is not there",10).show();
}
}
public void onDestroy() {
super.onDestroy();
if (mCamera != null) {
cameraParameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(cameraParameters);
mCamera.stopPreview();
mCamera.release();
}
Log.i("cameraFlashLight", "onDestroy");
}
}
Use this sequence of code:
mCamera = Camera.open();
cameraParameters = mCamera.getParameters();
cameraParameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(parameters);
mCamera.startPreview();

Categories

Resources