The following code is in service that takes picture in background. It is working fine for all the version below lollipop but gives run-time exception in takePicture(null,null,mcall). Any ideas..?
public void takePictures(final int delay)
{
final Camera.PictureCallback mCall = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.e(TAG, "Picture taken, saving....");
Uri uriTarget = getContentResolver().insert//(Media.EXTERNAL_CONTENT_URI, image);
(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Log.e("Image saved: ", uriTarget.toString());
savePictures(getRealPathFromURI(uriTarget.toString()));
mCamera.stopPreview();
mCamera.release();
mCamera = null;
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e("Image not saved: ", e.toString());
} catch (IOException e) {
Log.e("Image not saved:2 ", e.toString());
e.printStackTrace();
}
}
};
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
thread = new Thread(new Runnable() {
#Override
public void run() {
for (int numOfPicturesAlreadyTaken = 0; numOfPicturesAlreadyTaken < numOfPictures; numOfPicturesAlreadyTaken++) {
Log.e(TAG, "Opening camera");
mCamera = Camera.open();
//mCamera.setPreviewDisplay(sv.getHolder());
parameters = mCamera.getParameters();
parameters.setRotation(90);
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
Thread.sleep(delay);
}
}
});
thread.start();
} else {
Toast.makeText(this, "No camera found.", Toast.LENGTH_SHORT).show();
}
}
the error
come in lollipop only
the code is in service that take picture in background .
java.lang.RuntimeException: takePicture failed
at android.hardware.Camera.native_takePicture(Native Method)
at android.hardware.Camera.takePicture(Camera.java:1436)
at android.hardware.Camera.takePicture(Camera.java:1381)
at com.codebrew.lockdown.services.CameraService$2.run(CameraService.java:133)
at java.lang.Thread.run(Thread.java:818)
Related
Is there any way to get photo without preview and put it to database in android sdk 19
In the below code automaticly getting location on every 5 minutes and putting marker on map additionally i need to take photo automaticly and put it to database
public void startCountDown() {
if (this._countDownTimer != null) {
this._countDownTimer.cancel();
}
_countDownTimer = new CountDownTimer(60000 * 5, 60000*5) {
#Override
public void onFinish() {
}
#Override
public void onTick(long millisUntilFinished) {
putMarkerToLocation();
takePhotoAndSaveIt2Db(); // ==> here what i need
}
}.start();
}
Below service works percfectly on api19
public class CapPhoto extends Service {
private Camera mCamera;
#Override
public void onCreate() {
super.onCreate();
Log.d("CAM", "start");
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Thread myThread = null;
}
#Override
public void onStart(Intent intent, int startId) {
takePhoto();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void takePhoto() {
System.out.println("Fotoraf Cekimi Hazirligi Basladi");
Camera camera = null;
int cameraCount = 0;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
SystemClock.sleep(1000);
Camera.getCameraInfo(camIdx, cameraInfo);
try {
camera = Camera.open(camIdx);
} catch (RuntimeException e) {
System.out.println("Camera not available: " + camIdx);
camera = null;
//e.printStackTrace();
}
try {
if (null == camera) {
System.out.println("Could not get camera instance");
} else {
System.out.println("Got the camera, creating the dummy surface texture");
//SurfaceTexture dummySurfaceTextureF = new SurfaceTexture(0);
try {
//camera.setPreviewTexture(dummySurfaceTextureF);
camera.setPreviewTexture(new SurfaceTexture(0));
camera.startPreview();
} catch (Exception e) {
System.out.println("Could not set the surface preview texture");
e.printStackTrace();
}
camIdx = cameraCount;
Camera.Parameters params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
params.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
params.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
params.setExposureCompensation(0);
params.setPictureFormat(ImageFormat.JPEG);
params.setJpegQuality(100);
params.setRotation(90);
camera.setParameters(params);
camera.takePicture(null, null, new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFileDir =new File(Environment.getExternalStorageDirectory(), "A");
if(!pictureFileDir.exists()){
pictureFileDir.mkdirs();
} // File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "TaksiResim_" + "_" + date + ".jpg";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File mainPicture = new File(filename);
//addImageFile(mainPicture);
try {
FileOutputStream fos = new FileOutputStream(mainPicture);
fos.write(data);
fos.close();
System.out.println("resim kayit edildi");
} catch (Exception error) {
System.out.println("resim kayit edilemedi");
}
camera.release();
}
});
}
} catch (Exception e) {
camera.release();
}
}
} }
I have made a camera demo application in android. It was working fine on a button click event. But now I want to open the camera when activity starts and its not working. It fails with an error
Failed to connect to camera service
Please have a look at my code and save me. My code is as below:
code
surfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
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() {
#SuppressLint("NewApi")
public void onPictureTaken(byte[] data, Camera camera) {
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);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
bmp = BitmapFactory.decodeByteArray(data, 0, data.length,
options);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d("Log", "onPictureTaken - jpeg");
}
};
start_camera();
private void start_camera() {
try {
releaseCameraAndPreview();
camera = Camera.open();
camera.setDisplayOrientation(90);
} catch (RuntimeException e) {
Log.e(tag, "init_camera: " + e);
return;
}
param = camera.getParameters();
param.set("jpeg-quality", 100);
camera.setParameters(param);
// modify parameter
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
// camera.takePicture(shutter, raw, jpeg)
} catch (Exception e) {
Log.e(tag, "init_camera: " + e);
return;
}
}
I am using the Surface View and Surface Holder for opening the USB camera. Camera opening but after some time, I am getting "Error 100, Camera server died". I search lots of tutorials but error is not resolving. If anyone knows about this error please help me.
I am using below code for opening the camera.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button)findViewById(R.id.start);
start.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View arg0) {
start_camera();
}
});
surfaceView = (SurfaceView)findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d("Log", "onPictureTaken - raw");
}
};
}
private void start_camera()
{
try{
camera = Camera.open(0);
}catch(RuntimeException e){
Log.e(tag, "init_camera: 2=" + e);
return;
}
Camera.Parameters param;
param = camera.getParameters();
//modify parameter
param.setPreviewFrameRate(20);
param.setPreviewSize(640, 480);
camera.setParameters(param);
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception e) {
return;
}
}
mCamera = Camera.open(mCameraId);
mCamera.setErrorCallback(new Camera.ErrorCallback() {
#Override
public void onError(int error, Camera camera) {
KLog.e("相机服务出错,错误代码:" + error);
switch (error) {
case Camera.CAMERA_ERROR_SERVER_DIED:
case Camera.CAMERA_ERROR_UNKNOWN:
try {
mCamera.setPreviewCallback(null);
mCamera.setPreviewDisplay(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
start();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
});
I have this code, but it gives me this:
Unknown URI: content://media/external/images/media
NOTE: I DO have permissions for Camera / Write.
This is my code:
public class MainActivity extends Activity {
// ...
Camera.PictureCallback photoCallback=new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(getApplicationContext(),
"Image saved: " + uriTarget.toString(),
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finish();
}
};
// ...
}
Any suggestions?
// Here is the example for surface view.
public void takePictureNoPreview(Context context) { // open back facing camera by default
Camera myCamera=Camera.open();
if(myCamera!=null) {
try { // set camera parameters if you want to
// here, the unused surface view and holder
SurfaceView dummy=new SurfaceView(context);
myCamera.setPreviewDisplay(dummy.getHolder());
myCamera.startPreview();
myCamera.takePicture(null, null, getJpegCallback());
} finally {
myCamera.close();
}
} else {
// booo, failed!
}
}
private PictureCallback getJpegCallback() {
PictureCallback jpeg = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream fos;
try {
fos = new FileOutputStream("test.jpeg");
fos.write(data); fos.close();
} catch (IOException e) {
//do something about it
}
}
};
return jpeg;
}
// Selecting front facing camera.
private Camera openFrontFacingCameraGingerbread() {
int cameraCount = 0; Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for ( int camIdx = 0; camIdx < cameraCount; camIdx++ ) {
Camera.getCameraInfo( camIdx, cameraInfo );
if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ) {
try {
cam = Camera.open( camIdx );
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
// This should work...
I am trying to do an application that takes a picture with the front facing camera without a UI and i have been successful doing that but the only problem is the picture is always taken in landscape mode, is there any ways to force it to portrait mode?
public class TakePicture extends Activity implements SurfaceHolder.Callback
{
private ImageView iv_image;
private SurfaceView sv;
private Bitmap bmp;
private SurfaceHolder sHolder;
private Camera mCamera;
private int cameraId = 1;
private Parameters parameters;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv_image = (ImageView) findViewById(R.id.imageView);
sv = (SurfaceView) findViewById(R.id.surfaceView);
sHolder = sv.getHolder();
sHolder.addCallback(this);
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
parameters = mCamera.getParameters();
mCamera.setParameters(parameters);
mCamera.startPreview();
//mCamera.setDisplayOrientation(90);
//sets what code should be executed after the picture is taken
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
Log.d("DEBUG", "Can't create directory to save image.");
Toast.makeText(TakePicture.this, "Can't create directory to save image.",
Toast.LENGTH_LONG).show();
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "Picture_" + date + ".jpg";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast.makeText(TakePicture.this, "New Image saved:" + photoFile,
Toast.LENGTH_LONG).show();
finish();
} catch (Exception error) {
Log.d("DEBUG", "File" + filename + "not saved: "
+ error.getMessage());
Toast.makeText(TakePicture.this, "Image could not be saved.",
Toast.LENGTH_LONG).show();
}
}
};
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.
//mCamera = Camera.open();
mCamera = Camera.open(cameraId);
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
public void surfaceDestroyed(SurfaceHolder holder)
{
//stop the preview
mCamera.stopPreview();
//release the camera
mCamera.release();
//unbind the camera from this object
mCamera = null;
}
private File getDir() {
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "Camera!");
}
}
As far as I remember when trying to do this, it was a bit tricky.
One approach I found was:
public void surfaceCreated(SurfaceHolder holder) {
mCamera = Camera.open();
Parameters params = mCamera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
params.set("orientation", "portrait");
try {
//not sure if this block of code had an OR relationship with the previous line params.set("orientation", "portrait");
Method rotateSet = Camera.Parameters.class.getMethod("setRotation", new Class[] { Integer.TYPE });
Object arguments[] = new Object[] { new Integer(90) };
rotateSet.invoke(params, arguments);
} catch (Exception e) {
e.printStackTrace();
}
}
mCamera.setParameters(params);
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
But it didn't work for me (althought I was using Android version higher than 2.0, where this was supposed to work).
I also found a hack using reflection, and that worked:
public void surfaceCreated(SurfaceHolder holder) {
mCamera = Camera.open();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {}
setDisplayOrientation(mCamera, 90);
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
Where setDisplayOrientation is:
protected void setDisplayOrientation(Camera camera, int angle){
Method setDisplayOrientationMethod;
try {
setDisplayOrientationMethod = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
if (setDisplayOrientationMethod != null) {
setDisplayOrientationMethod.invoke(camera, new Object[] {angle});
}
} catch (Exception e1) {}
}