I have an android app which consists of a Button.
When you click on Button, an image should be captured from the camera without opening the camera application (the image should be captured in background).
How to implement this feature?
Any suggestions will be of great help.
Thanks a lot in advance.
Here is my whole working project of How to capture image in background without SurfaceView.
// You can start your service to capturing image wherever you want not should from activity.
also need to ask need permission in your Activity
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, APP_PERMISSION_REQUEST);
}
handle intent in click or where you needed
Intent front_translucent = new Intent(getApplication()
.getApplicationContext(), CameraService.class);
front_translucent.putExtra("Front_Request", true);
front_translucent.putExtra("Quality_Mode",
camCapture.getQuality());
getApplication().getApplicationContext().startService(
front_translucent);
public class CamerService extends Service implements
SurfaceHolder.Callback {
// Camera variables
// a surface holder
// a variable to control the camera
private Camera mCamera;
// the camera parameters
private Parameters parameters;
private Bitmap bmp;
FileOutputStream fo;
private String FLASH_MODE;
private int QUALITY_MODE = 0;
private boolean isFrontCamRequest = false;
private Camera.Size pictureSize;
SurfaceView sv;
private SurfaceHolder sHolder;
private WindowManager windowManager;
WindowManager.LayoutParams params;
public Intent cameraIntent;
SharedPreferences pref;
Editor editor;
int width = 0, height = 0;
/** Called when the activity is first created. */
#Override
public void onCreate() {
super.onCreate();
}
private Camera openFrontFacingCameraGingerbread() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
}
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("Camera",
"Camera failed to open: " + e.getLocalizedMessage());
/*
* Toast.makeText(getApplicationContext(),
* "Front Camera failed to open", Toast.LENGTH_LONG)
* .show();
*/
}
}
}
return cam;
}
private void setBesttPictureResolution() {
// get biggest picture size
width = pref.getInt("Picture_Width", 0);
height = pref.getInt("Picture_height", 0);
if (width == 0 | height == 0) {
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// save width and height in sharedprefrences
width = pictureSize.width;
height = pictureSize.height;
editor.putInt("Picture_Width", width);
editor.putInt("Picture_height", height);
editor.commit();
} else {
// if (pictureSize != null)
parameters.setPictureSize(width, height);
}
}
private Camera.Size getBiggesttPictureSize(Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPictureSizes()) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
return (result);
}
/** 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;
}
}
/** Check if this device has front camera */
private boolean checkFrontCamera(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FRONT)) {
// this device has front camera
return true;
} else {
// no front camera on this device
return false;
}
}
Handler handler = new Handler();
private class TakeImage extends AsyncTask<Intent, Void, Void> {
#Override
protected Void doInBackground(Intent... params) {
takeImage(params[0]);
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
private synchronized void takeImage(Intent intent) {
if (checkCameraHardware(getApplicationContext())) {
Bundle extras = intent.getExtras();
if (extras != null) {
String flash_mode = extras.getString("FLASH");
FLASH_MODE = flash_mode;
boolean front_cam_req = extras.getBoolean("Front_Request");
isFrontCamRequest = front_cam_req;
int quality_mode = extras.getInt("Quality_Mode");
QUALITY_MODE = quality_mode;
}
if (isFrontCamRequest) {
// set flash 0ff
FLASH_MODE = "off";
// only for gingerbread and newer versions
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
mCamera = openFrontFacingCameraGingerbread();
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(sv.getHolder());
} catch (IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"API dosen't support front camera",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
Camera.Parameters parameters = mCamera.getParameters();
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
// return 4;
} else {
mCamera = null;
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"Your Device dosen't have Front Camera !",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
/*
* sHolder = sv.getHolder(); // tells Android that this
* surface will have its data // constantly // replaced if
* (Build.VERSION.SDK_INT < 11)
*
* sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)
*/
} else {
if (checkFrontCamera(getApplicationContext())) {
mCamera = openFrontFacingCameraGingerbread();
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(sv.getHolder());
} catch (IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"API dosen't support front camera",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
Camera.Parameters parameters = mCamera.getParameters();
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
// return 4;
} else {
mCamera = null;
/*
* Toast.makeText(getApplicationContext(),
* "API dosen't support front camera",
* Toast.LENGTH_LONG).show();
*/
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"Your Device dosen't have Front Camera !",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
// Get a surface
/*
* sHolder = sv.getHolder(); // tells Android that this
* surface will have its data // constantly // replaced
* if (Build.VERSION.SDK_INT < 11)
*
* sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS
* );
*/
}
}
} else {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = Camera.open();
} else
mCamera = getCameraInstance();
try {
if (mCamera != null) {
mCamera.setPreviewDisplay(sv.getHolder());
parameters = mCamera.getParameters();
if (FLASH_MODE == null || FLASH_MODE.isEmpty()) {
FLASH_MODE = "auto";
}
parameters.setFlashMode(FLASH_MODE);
// set biggest picture
setBesttPictureResolution();
// log quality and image format
Log.d("Qaulity", parameters.getJpegQuality() + "");
Log.d("Format", parameters.getPictureFormat() + "");
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
Log.d("ImageTakin", "OnTake()");
mCamera.takePicture(null, null, mCall);
} else {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Camera is unavailable !",
Toast.LENGTH_LONG).show();
}
});
}
// return 4;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TAG", "CmaraHeadService()::takePicture", e);
}
// Get a surface
/*
* sHolder = sv.getHolder(); // tells Android that this surface
* will have its data constantly // replaced if
* (Build.VERSION.SDK_INT < 11)
*
* sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
*/
}
} else {
// display in long period of time
/*
* Toast.makeText(getApplicationContext(),
* "Your Device dosen't have a Camera !", Toast.LENGTH_LONG)
* .show();
*/
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Your Device dosen't have a Camera !",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
// return super.onStartCommand(intent, flags, startId);
}
#SuppressWarnings("deprecation")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// sv = new SurfaceView(getApplicationContext());
cameraIntent = intent;
Log.d("ImageTakin", "StartCommand()");
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.width = 1;
params.height = 1;
params.x = 0;
params.y = 0;
sv = new SurfaceView(getApplicationContext());
windowManager.addView(sv, params);
sHolder = sv.getHolder();
sHolder.addCallback(this);
// tells Android that this surface will have its data constantly
// replaced
if (Build.VERSION.SDK_INT < 11)
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
return 1;
}
Camera.PictureCallback mCall = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// decode the data obtained by the camera into a Bitmap
Log.d("ImageTakin", "Done");
if (bmp != null)
bmp.recycle();
System.gc();
bmp = decodeBitmap(data);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (bmp != null && QUALITY_MODE == 0)
bmp.compress(Bitmap.CompressFormat.JPEG, 70, bytes);
else if (bmp != null && QUALITY_MODE != 0)
bmp.compress(Bitmap.CompressFormat.JPEG, QUALITY_MODE, bytes);
File imagesFolder = new File(
Environment.getExternalStorageDirectory(), "MYGALLERY");
if (!imagesFolder.exists())
imagesFolder.mkdirs(); // <----
File image = new File(imagesFolder, System.currentTimeMillis()
+ ".jpg");
// write the bytes in file
try {
fo = new FileOutputStream(image);
} catch (FileNotFoundException e) {
Log.e("TAG", "FileNotFoundException", e);
// TODO Auto-generated catch block
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
Log.e("TAG", "fo.write::PictureTaken", e);
// TODO Auto-generated catch block
}
// remember close de FileOutput
try {
fo.close();
if (Build.VERSION.SDK_INT < 19)
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
else {
MediaScannerConnection
.scanFile(
getApplicationContext(),
new String[] { image.toString() },
null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(
String path, Uri uri) {
Log.i("ExternalStorage", "Scanned "
+ path + ":");
Log.i("ExternalStorage", "-> uri="
+ uri);
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
/*
* Toast.makeText(getApplicationContext(),
* "Your Picture has been taken !", Toast.LENGTH_LONG).show();
*/
com.integreight.onesheeld.Log.d("Camera", "Image Taken !");
if (bmp != null) {
bmp.recycle();
bmp = null;
System.gc();
}
mCamera = null;
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Your Picture has been taken !", Toast.LENGTH_SHORT)
.show();
}
});
stopSelf();
}
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
#Override
public void onDestroy() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
if (sv != null)
windowManager.removeView(sv);
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
super.onDestroy();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (cameraIntent != null)
new TakeImage().execute(cameraIntent);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
public static Bitmap decodeBitmap(byte[] data) {
Bitmap bitmap = null;
BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inDither = false; // Disable Dithering mode
bfOptions.inPurgeable = true; // Tell to gc that whether it needs free
// memory, the Bitmap can be cleared
bfOptions.inInputShareable = true; // Which kind of reference will be
// used to recover the Bitmap data
// after being clear, when it will
// be used in the future
bfOptions.inTempStorage = new byte[32 * 1024];
if (data != null)
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
bfOptions);
return bitmap;
}
}
You have to create a fake Surface view that doesn't appears to the users and then you can achieve by the following code
public class MainActivity extends Activity {
public static final int DONE = 1;
public static final int NEXT = 2;
public static final int PERIOD = 1;
private Camera camera;
private int cameraId = 0;
private ImageView display;
private Timer timer;
SurfaceHolder previewHolder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (ImageView) findViewById(R.id.imageView1);
// do we have a camera?
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))
{
Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
.show();
}
else
{
cameraId = findFrontFacingCamera();
if (cameraId < 0)
{
Toast.makeText(this, "No front facing camera found.",
Toast.LENGTH_LONG).show();
}
else
{
safeCameraOpen(cameraId);
}
}
// THIS IS JUST A FAKE SURFACE TO TRICK THE CAMERA PREVIEW
// http://stackoverflow.com/questions/17859777/how-to-take-pictures-in-android-
// application-without-the-user-interface
SurfaceView dummy = new SurfaceView(this);
previewHolder = dummy.getHolder();
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
try {
camera.setPreviewDisplay(previewHolder);
} catch (IOException e1) {
e1.printStackTrace();
}
/*SurfaceView view = new SurfaceView(this);
try {
// camera.setPreviewDisplay(view.getHolder());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
Camera.Parameters params = camera.getParameters();
params.setJpegQuality(100);
camera.setParameters(params);
// We need something to trigger periodically the capture of a
// picture to be processed
timer = new Timer(getApplicationContext(), threadHandler);
timer.execute();
}
// thread Handler //
private Handler threadHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case DONE:
camera.startPreview();
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
try {
camera.setPreviewDisplay(previewHolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
camera.takePicture(null, null, mCall);
break;
case NEXT:
timer = new Timer(getApplicationContext(), threadHandler);
timer.execute();
break;
}
}
};
Camera.PictureCallback mCall = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// decode the data obtained by the camera into a Bitmap
// display.setImageBitmap(photo);
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(data, 0,
data.length);
display.setImageBitmap(bitmapPicture);
Message.obtain(threadHandler, MainActivity.NEXT, "").sendToTarget();
// Log.v("MyActivity","Length: "+data.length);
}
};
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.v("MyActivity", "Camera found");
cameraId = i;
break;
}
}
return cameraId;
}
#Override
protected void onPause() {
if (timer != null) {
timer.cancel(true);
}
releaseCamera();
super.onPause();
}
// I think Android Documentation recommends doing this in a separate
// task to avoid blocking main UI
private boolean safeCameraOpen(int id) {
boolean qOpened = false;
try {
releaseCamera();
camera = Camera.open(id);
qOpened = (camera != null);
} catch (Exception e) {
Log.e(getString(R.string.app_name), "failed to open Camera");
e.printStackTrace();
}
return qOpened;
}
private void releaseCamera() {
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
}
If you are using CAMERA2 API (added in API 21), then kindly check my answer here Capture picture without preview using camera2 API
Hope that helped :)
You can do that using CameraX. It is used to create your own camera app so you can do that by just omitting the preview part. Go to the below link for a small tutorial on cameraX https://developer.android.com/codelabs/camerax-getting-started#0 and you can just copy paste the code. For androidx.camera.view.PreviewView just put width=0 and height=0 and you will get the required result.
Related
My application got crashed on devices with no SD cards in it, but is working fine with devices which are having SD card in it.When i debugged it, i found that on
mCamera.takePicture(null, null, jpegCallBack);
Method app is getting crashed with above error.I goggled a lot but didn't found any solution , i saw this link :-
http://forums.androidcentral.com/motorola-droid-x/102987-camera-won-t-take-pictures-without-sd-card.html
So is it possible to capture images in background service in device with no SD card in it.
Please provide me some clues
Here are some methods of my hiddenCamera class
#SuppressWarnings("deprecation")
private void startCapturingCall() {
final Boolean isSDPresent = android.os.Environment
.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
if (mCamera != null) {
parameters = mCamera.getParameters();
if (FLASH_MODE == null || FLASH_MODE.isEmpty()) {
FLASH_MODE = "auto";
}
parameters.setFlashMode(FLASH_MODE);
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
new Handler().postDelayed(new Runnable() {
#SuppressWarnings("deprecation")
#Override
public void run() {
if (isSDPresent) {
mCamera.takePicture(null, null, jpegCallBack);
} else {
Toast.makeText(getApplicationContext(),
"Please Insert SD card", 1000).show();
}
}
}, 2000);
}
}
#SuppressWarnings("deprecation")
Camera.PictureCallback jpegCallBack = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Boolean isSDPresent = android.os.Environment
.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
// checking for SD card
if (isSDPresent) {
mediaStorageDir = new File(Environment
.getExternalStorageDirectory().getAbsolutePath(),
IMAGE_DIRECTORY_NAME);
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
}
}
try {
Bitmap userImage = BitmapFactory.decodeByteArray(data, 0,
data.length);
// set file out stream
FileOutputStream out = new FileOutputStream(mediaFile);
// set compress format quality and stream
userImage.compress(Bitmap.CompressFormat.JPEG, 50, out);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
userImage.compress(Bitmap.CompressFormat.JPEG, 50, baos);
mByteArray = baos.toByteArray();
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),
"Please insert SD card !", Toast.LENGTH_LONG).show();
}
if (mediaStorageDir.exists()) {
getPathOfCapturedImage();
}
HiddenCamera.this.finish();
CameraService.IS_ACTIVITY_FINISHED = true;
}
};
And also isSDPresent always returns me true value .
Please provide me your suggestions on this. I am really stuck at this point from last 2-3 days.
This is the issue of Device too as in Samsung Grand , my code is working fine even its not having SD card in it.But in Moto E its my application getting crashed.Camera settings plays an important role in it.
Thanks
Finally i am done with this, though i got busy in some other task but today i get time to post my Answer on this topic, As this topis is very general , so i am posting this answer inorder to help others who might have thought of this functionality , So i done this thing by using SurfaceTexture but it will only work for versions greater thet 4 and for versions less than 4 you need to use surfaceView.
So here is my code :-
public class SurfaceTextureActivity extends Activity implements
SurfaceTextureListener {
private Parameters mParameters;
private Camera.Size mPictureSize;
private static final String sIMAGE_DIRECTORY_NAME = "HiddenCapturedPics";
private byte[] mByteArray;
private Camera mCamera;
private TextureView mTextureView;
private File mMediaFile, mMediaStorageDir = null;
private String mEncodedImage, mImageName, mFinalResponse,
mFlashMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextureView = new TextureView(this);
setContentView(mTextureView);
if (checkCameraHardware(getApplicationContext())) {
mTextureView.setSurfaceTextureListener(this);
Bundle extras = getIntent().getExtras();
mFlashMode = extras.getString("FLASH");
} else {
Toast.makeText(getApplicationContext(),
"Your Device dosen't have a Camera !", Toast.LENGTH_LONG)
.show();
}
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width,
int height) {
mCamera = Camera.open();
mTextureView.setLayoutParams(new FrameLayout.LayoutParams(0, 0,
Gravity.CENTER));
try {
mCamera.setPreviewTexture(surface);
} catch (IOException t) {
}
mCamera.startPreview();
startCapturingCall();
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width,
int height) {
// Ignored, the Camera does all the work for us
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
mCamera.stopPreview();
mCamera.release();
return true;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
Toast.makeText(getApplicationContext(), "Dfg", Toast.LENGTH_SHORT)
.show();
// Update your view here!
}
Camera.PictureCallback jpegCallBack = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Boolean isSDPresent = android.os.Environment
.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
// checking for SD card
if (isSDPresent) {
mMediaStorageDir = new File(Environment
.getExternalStorageDirectory().getAbsolutePath(),
sIMAGE_DIRECTORY_NAME);
mMediaFile = new File(mMediaStorageDir.getPath()
+ File.separator + "IMG_" + timeStamp + ".jpg");
if (!mMediaStorageDir.exists()) {
if (!mMediaStorageDir.mkdirs()) {
}
}
try {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap userImage = BitmapFactory.decodeByteArray(data, 0,
data.length, options);
FileOutputStream out = new FileOutputStream(mMediaFile);
userImage.compress(Bitmap.CompressFormat.JPEG, 50, out);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
userImage.compress(Bitmap.CompressFormat.JPEG, 50, baos);
mByteArray = baos.toByteArray();
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),
"Please insert SD card !", Toast.LENGTH_LONG).show();
}
if (mMediaStorageDir.exists()) {
getPathOfCapturedImage();
}
SurfaceTextureActivity.this.finish();
CameraService.IS_ACTIVITY_FINISHED = true;
}
};
private void startCapturingCall() {
if (mCamera != null) {
mParameters = mCamera.getParameters();
if (mFlashMode == null || mFlashMode.isEmpty()) {
mFlashMode = "auto";
}
mParameters.setFlashMode(mFlashMode);
mPictureSize = getBiggesttPictureSize(mParameters);
if (mPictureSize != null)
mParameters.setPictureSize(mPictureSize.width,
mPictureSize.height);
mCamera.setParameters(mParameters);
mCamera.startPreview();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (mCamera != null) {
mCamera.startPreview();
mCamera.takePicture(null, null, jpegCallBack);
} else {
mCamera = getCameraInstance();
mCamera.startPreview();
mCamera.takePicture(null, null, jpegCallBack);
}
}
}, 2000);
}
}
private Camera.Size getBiggesttPictureSize(Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPictureSizes()) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
return (result);
}
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
}
}
Hope this will help others .......
Here are the links for reference :-
Example of Camera preview using SurfaceTexture in Android
Camera.takePicture throws RunTimeException
Cheers!!!!!
I have an android app which consists of a Button.
When you click on Button, an image should be captured from the camera without opening the camera application (the image should be captured in background).
How to implement this feature?
Any suggestions will be of great help.
Thanks a lot in advance.
Here is my whole working project of How to capture image in background without SurfaceView.
// You can start your service to capturing image wherever you want not should from activity.
also need to ask need permission in your Activity
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, APP_PERMISSION_REQUEST);
}
handle intent in click or where you needed
Intent front_translucent = new Intent(getApplication()
.getApplicationContext(), CameraService.class);
front_translucent.putExtra("Front_Request", true);
front_translucent.putExtra("Quality_Mode",
camCapture.getQuality());
getApplication().getApplicationContext().startService(
front_translucent);
public class CamerService extends Service implements
SurfaceHolder.Callback {
// Camera variables
// a surface holder
// a variable to control the camera
private Camera mCamera;
// the camera parameters
private Parameters parameters;
private Bitmap bmp;
FileOutputStream fo;
private String FLASH_MODE;
private int QUALITY_MODE = 0;
private boolean isFrontCamRequest = false;
private Camera.Size pictureSize;
SurfaceView sv;
private SurfaceHolder sHolder;
private WindowManager windowManager;
WindowManager.LayoutParams params;
public Intent cameraIntent;
SharedPreferences pref;
Editor editor;
int width = 0, height = 0;
/** Called when the activity is first created. */
#Override
public void onCreate() {
super.onCreate();
}
private Camera openFrontFacingCameraGingerbread() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
}
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("Camera",
"Camera failed to open: " + e.getLocalizedMessage());
/*
* Toast.makeText(getApplicationContext(),
* "Front Camera failed to open", Toast.LENGTH_LONG)
* .show();
*/
}
}
}
return cam;
}
private void setBesttPictureResolution() {
// get biggest picture size
width = pref.getInt("Picture_Width", 0);
height = pref.getInt("Picture_height", 0);
if (width == 0 | height == 0) {
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// save width and height in sharedprefrences
width = pictureSize.width;
height = pictureSize.height;
editor.putInt("Picture_Width", width);
editor.putInt("Picture_height", height);
editor.commit();
} else {
// if (pictureSize != null)
parameters.setPictureSize(width, height);
}
}
private Camera.Size getBiggesttPictureSize(Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPictureSizes()) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
return (result);
}
/** 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;
}
}
/** Check if this device has front camera */
private boolean checkFrontCamera(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FRONT)) {
// this device has front camera
return true;
} else {
// no front camera on this device
return false;
}
}
Handler handler = new Handler();
private class TakeImage extends AsyncTask<Intent, Void, Void> {
#Override
protected Void doInBackground(Intent... params) {
takeImage(params[0]);
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
private synchronized void takeImage(Intent intent) {
if (checkCameraHardware(getApplicationContext())) {
Bundle extras = intent.getExtras();
if (extras != null) {
String flash_mode = extras.getString("FLASH");
FLASH_MODE = flash_mode;
boolean front_cam_req = extras.getBoolean("Front_Request");
isFrontCamRequest = front_cam_req;
int quality_mode = extras.getInt("Quality_Mode");
QUALITY_MODE = quality_mode;
}
if (isFrontCamRequest) {
// set flash 0ff
FLASH_MODE = "off";
// only for gingerbread and newer versions
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
mCamera = openFrontFacingCameraGingerbread();
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(sv.getHolder());
} catch (IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"API dosen't support front camera",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
Camera.Parameters parameters = mCamera.getParameters();
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
// return 4;
} else {
mCamera = null;
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"Your Device dosen't have Front Camera !",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
/*
* sHolder = sv.getHolder(); // tells Android that this
* surface will have its data // constantly // replaced if
* (Build.VERSION.SDK_INT < 11)
*
* sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)
*/
} else {
if (checkFrontCamera(getApplicationContext())) {
mCamera = openFrontFacingCameraGingerbread();
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(sv.getHolder());
} catch (IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"API dosen't support front camera",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
Camera.Parameters parameters = mCamera.getParameters();
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
// return 4;
} else {
mCamera = null;
/*
* Toast.makeText(getApplicationContext(),
* "API dosen't support front camera",
* Toast.LENGTH_LONG).show();
*/
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"Your Device dosen't have Front Camera !",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
// Get a surface
/*
* sHolder = sv.getHolder(); // tells Android that this
* surface will have its data // constantly // replaced
* if (Build.VERSION.SDK_INT < 11)
*
* sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS
* );
*/
}
}
} else {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = Camera.open();
} else
mCamera = getCameraInstance();
try {
if (mCamera != null) {
mCamera.setPreviewDisplay(sv.getHolder());
parameters = mCamera.getParameters();
if (FLASH_MODE == null || FLASH_MODE.isEmpty()) {
FLASH_MODE = "auto";
}
parameters.setFlashMode(FLASH_MODE);
// set biggest picture
setBesttPictureResolution();
// log quality and image format
Log.d("Qaulity", parameters.getJpegQuality() + "");
Log.d("Format", parameters.getPictureFormat() + "");
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
Log.d("ImageTakin", "OnTake()");
mCamera.takePicture(null, null, mCall);
} else {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Camera is unavailable !",
Toast.LENGTH_LONG).show();
}
});
}
// return 4;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TAG", "CmaraHeadService()::takePicture", e);
}
// Get a surface
/*
* sHolder = sv.getHolder(); // tells Android that this surface
* will have its data constantly // replaced if
* (Build.VERSION.SDK_INT < 11)
*
* sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
*/
}
} else {
// display in long period of time
/*
* Toast.makeText(getApplicationContext(),
* "Your Device dosen't have a Camera !", Toast.LENGTH_LONG)
* .show();
*/
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Your Device dosen't have a Camera !",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
// return super.onStartCommand(intent, flags, startId);
}
#SuppressWarnings("deprecation")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// sv = new SurfaceView(getApplicationContext());
cameraIntent = intent;
Log.d("ImageTakin", "StartCommand()");
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.width = 1;
params.height = 1;
params.x = 0;
params.y = 0;
sv = new SurfaceView(getApplicationContext());
windowManager.addView(sv, params);
sHolder = sv.getHolder();
sHolder.addCallback(this);
// tells Android that this surface will have its data constantly
// replaced
if (Build.VERSION.SDK_INT < 11)
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
return 1;
}
Camera.PictureCallback mCall = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// decode the data obtained by the camera into a Bitmap
Log.d("ImageTakin", "Done");
if (bmp != null)
bmp.recycle();
System.gc();
bmp = decodeBitmap(data);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (bmp != null && QUALITY_MODE == 0)
bmp.compress(Bitmap.CompressFormat.JPEG, 70, bytes);
else if (bmp != null && QUALITY_MODE != 0)
bmp.compress(Bitmap.CompressFormat.JPEG, QUALITY_MODE, bytes);
File imagesFolder = new File(
Environment.getExternalStorageDirectory(), "MYGALLERY");
if (!imagesFolder.exists())
imagesFolder.mkdirs(); // <----
File image = new File(imagesFolder, System.currentTimeMillis()
+ ".jpg");
// write the bytes in file
try {
fo = new FileOutputStream(image);
} catch (FileNotFoundException e) {
Log.e("TAG", "FileNotFoundException", e);
// TODO Auto-generated catch block
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
Log.e("TAG", "fo.write::PictureTaken", e);
// TODO Auto-generated catch block
}
// remember close de FileOutput
try {
fo.close();
if (Build.VERSION.SDK_INT < 19)
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
else {
MediaScannerConnection
.scanFile(
getApplicationContext(),
new String[] { image.toString() },
null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(
String path, Uri uri) {
Log.i("ExternalStorage", "Scanned "
+ path + ":");
Log.i("ExternalStorage", "-> uri="
+ uri);
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
/*
* Toast.makeText(getApplicationContext(),
* "Your Picture has been taken !", Toast.LENGTH_LONG).show();
*/
com.integreight.onesheeld.Log.d("Camera", "Image Taken !");
if (bmp != null) {
bmp.recycle();
bmp = null;
System.gc();
}
mCamera = null;
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Your Picture has been taken !", Toast.LENGTH_SHORT)
.show();
}
});
stopSelf();
}
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
#Override
public void onDestroy() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
if (sv != null)
windowManager.removeView(sv);
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
super.onDestroy();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (cameraIntent != null)
new TakeImage().execute(cameraIntent);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
public static Bitmap decodeBitmap(byte[] data) {
Bitmap bitmap = null;
BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inDither = false; // Disable Dithering mode
bfOptions.inPurgeable = true; // Tell to gc that whether it needs free
// memory, the Bitmap can be cleared
bfOptions.inInputShareable = true; // Which kind of reference will be
// used to recover the Bitmap data
// after being clear, when it will
// be used in the future
bfOptions.inTempStorage = new byte[32 * 1024];
if (data != null)
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
bfOptions);
return bitmap;
}
}
You have to create a fake Surface view that doesn't appears to the users and then you can achieve by the following code
public class MainActivity extends Activity {
public static final int DONE = 1;
public static final int NEXT = 2;
public static final int PERIOD = 1;
private Camera camera;
private int cameraId = 0;
private ImageView display;
private Timer timer;
SurfaceHolder previewHolder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (ImageView) findViewById(R.id.imageView1);
// do we have a camera?
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))
{
Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
.show();
}
else
{
cameraId = findFrontFacingCamera();
if (cameraId < 0)
{
Toast.makeText(this, "No front facing camera found.",
Toast.LENGTH_LONG).show();
}
else
{
safeCameraOpen(cameraId);
}
}
// THIS IS JUST A FAKE SURFACE TO TRICK THE CAMERA PREVIEW
// http://stackoverflow.com/questions/17859777/how-to-take-pictures-in-android-
// application-without-the-user-interface
SurfaceView dummy = new SurfaceView(this);
previewHolder = dummy.getHolder();
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
try {
camera.setPreviewDisplay(previewHolder);
} catch (IOException e1) {
e1.printStackTrace();
}
/*SurfaceView view = new SurfaceView(this);
try {
// camera.setPreviewDisplay(view.getHolder());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
Camera.Parameters params = camera.getParameters();
params.setJpegQuality(100);
camera.setParameters(params);
// We need something to trigger periodically the capture of a
// picture to be processed
timer = new Timer(getApplicationContext(), threadHandler);
timer.execute();
}
// thread Handler //
private Handler threadHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case DONE:
camera.startPreview();
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
try {
camera.setPreviewDisplay(previewHolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
camera.takePicture(null, null, mCall);
break;
case NEXT:
timer = new Timer(getApplicationContext(), threadHandler);
timer.execute();
break;
}
}
};
Camera.PictureCallback mCall = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// decode the data obtained by the camera into a Bitmap
// display.setImageBitmap(photo);
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(data, 0,
data.length);
display.setImageBitmap(bitmapPicture);
Message.obtain(threadHandler, MainActivity.NEXT, "").sendToTarget();
// Log.v("MyActivity","Length: "+data.length);
}
};
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.v("MyActivity", "Camera found");
cameraId = i;
break;
}
}
return cameraId;
}
#Override
protected void onPause() {
if (timer != null) {
timer.cancel(true);
}
releaseCamera();
super.onPause();
}
// I think Android Documentation recommends doing this in a separate
// task to avoid blocking main UI
private boolean safeCameraOpen(int id) {
boolean qOpened = false;
try {
releaseCamera();
camera = Camera.open(id);
qOpened = (camera != null);
} catch (Exception e) {
Log.e(getString(R.string.app_name), "failed to open Camera");
e.printStackTrace();
}
return qOpened;
}
private void releaseCamera() {
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
}
If you are using CAMERA2 API (added in API 21), then kindly check my answer here Capture picture without preview using camera2 API
Hope that helped :)
You can do that using CameraX. It is used to create your own camera app so you can do that by just omitting the preview part. Go to the below link for a small tutorial on cameraX https://developer.android.com/codelabs/camerax-getting-started#0 and you can just copy paste the code. For androidx.camera.view.PreviewView just put width=0 and height=0 and you will get the required result.
i am try to to capture image,which previews in a surfaceview and there is a button by which picture taken and save onto memory card.preview and capture works well but not able to store on memory card..
there are created file but picture not store one by one...
plz help me...
my try one is here....
public class MainActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
Camera mCamera;
private CameraView cameraview;
RelativeLayout mainlayout;
ImageView capture;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cameraview = new CameraView(this, CameraInfo.CAMERA_FACING_BACK);
setContentView(R.layout.activity_main);
mainlayout = (RelativeLayout) findViewById(R.id.mainlayout);
mainlayout.addView(cameraview);
capture=(ImageView)findViewById(R.id.capture);
/////////////////////////////////////////////////////////
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
capture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
cameraview.mCamera.takePicture(shutterCallback, rawCallback,
jpegCallback);
Toast.makeText(getApplicationContext(), "Captured", 2000).show();
}
});
}
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 {
outStream = new FileOutputStream(String.format(
"/sdcard/Demo%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
and my CameraView class is here..
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder mHolder;
Camera mCamera;
int mCameraFacingInfo;
Context m_context;
public CameraView(Context context, int camereface) {
super(context);
// TODO Auto-generated constructor stub
m_context = context;
mCameraFacingInfo = camereface;
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (mCamera != null) {
int rotation = ((Activity) m_context).getWindowManager()
.getDefaultDisplay().getRotation();
if (rotation == Surface.ROTATION_0
|| rotation == Surface.ROTATION_180) {
mCamera.setDisplayOrientation(90);
} else if (rotation == Surface.ROTATION_90) {
mCamera.setDisplayOrientation(0);
} else if (rotation == Surface.ROTATION_270) {
mCamera.setDisplayOrientation(180);
}
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(width, height);
// mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
// ////////////////////////////////////////////////////
/*mCamera.setCameraViewDisplay(holder);
mCamera.setCameraViewCallback(new CameraViewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
//
CameraView.this.invalidate();
}
});
*/
// //////////////////////////////////////////
synchronized (this) {
int cameraFacingInfo = -1;
boolean errorFound = false;
boolean hasFeatCamera = m_context.getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if (hasFeatCamera) {
try {
cameraFacingInfo = mCameraFacingInfo;
mCamera = Camera.open(cameraFacingInfo);
} catch (Exception e) {
mCamera = Camera.open(0);
}
} else if (CameraInfo.CAMERA_FACING_FRONT > -1) {
try {
cameraFacingInfo = CameraInfo.CAMERA_FACING_FRONT;
mCamera = Camera.open(cameraFacingInfo);
} catch (Exception e) {
errorFound = true;
}
if (errorFound == true) {
try {
mCamera = Camera.open(0);
cameraFacingInfo = 0;
} catch (Exception e) {
cameraFacingInfo = -1;
}
}
}
if (cameraFacingInfo < 0) {
Toast.makeText(m_context, "No camera found.", Toast.LENGTH_LONG)
.show();
}
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(holder);
int rotation = ((Activity) m_context).getWindowManager()
.getDefaultDisplay().getRotation();
if (rotation == Surface.ROTATION_0
|| rotation == Surface.ROTATION_180) {
// Log.i(TAG, "0");
mCamera.setDisplayOrientation(90);
} else if (rotation == Surface.ROTATION_90) {
// Log.i(TAG, "90");
mCamera.setDisplayOrientation(0);
} else if (rotation == Surface.ROTATION_270) {
// Log.i(TAG, "270");
mCamera.setDisplayOrientation(180);
}
} catch (IOException exception) {
mCamera.release();
mCamera = null;
// TODO: add more exception handling logic here
}
}
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
public void setCameraFacingInfo(int cameraFacingInfo) {
mCameraFacingInfo = cameraFacingInfo;
}
}
Try to change your jpegCallback class to this:
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//Creating empty file in sdcard
File pictureFile = new File(String.format("/sdcard/Demo%d.jpg", System.currentTimeMillis()));
if (pictureFile == null) {
Log.e("IMAGE CAPTURE", "Error creating media file, check storage permissions: ");
return;
}
if (data != null) {
BitmapFactory.Options opts = new BitmapFactory.Options();
ActivityManager activityManager = (ActivityManager) MainActivity.this.getSystemService(Activity.ACTIVITY_SERVICE);
int memoryLimit = 100;
if (activityManager != null) {
memoryLimit = activityManager.getMemoryClass();
}
// Considering memory limitation of device we will resize image to prevent OutOfMemory
if (memoryLimit < 20) {
opts.inSampleSize = 6;
} else if (memoryLimit < 40) {
opts.inSampleSize = 4;
} else if (memoryLimit < 64) {
opts.inSampleSize = 2;
}
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)) {
fos.close();
}
bitmap.recycle();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
}
I am creating small app which previews camera and when clicking on screen saves image.
My problem is when image is saved, I want to start different activity which will do preview and have some tools on it. But what ever I do activity doesn't start.
Here is my code
public class CameraActivity extends Activity {
private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera = null;
private boolean inPreview = false;
private boolean cameraConfigured = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
preview = (SurfaceView) findViewById(R.id.preview);
Button button = (Button) findViewById(R.id.button_capture);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (camera != null) {
camera.takePicture(null, null, photoCallback);
onPause();
Intent intent = new Intent(CameraActivity.this, PreviewAndSaveActivity.class);
intent.putExtra("image", "");
CameraActivity.this.startActivity(intent);
}
}
});
previewHolder = preview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void onResume() {
super.onResume();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
Camera.CameraInfo info = new Camera.CameraInfo();
for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
camera = Camera.open(i);
}
}
}
if (camera == null) {
camera = Camera.open();
}
startPreview();
}
#Override
public void onPause() {
if (camera != null) {
if (inPreview) {
camera.stopPreview();
}
camera.release();
camera = null;
}
inPreview = false;
super.onPause();
}
private Camera.Size getBestPreviewSize(int width, int height,
Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
if (size.width <= width && size.height <= height) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
}
return (result);
}
private Camera.Size getSmallestPictureSize(Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPictureSizes()) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea < resultArea) {
result = size;
}
}
}
return (result);
}
private void initPreview(int width, int height) {
if (camera != null && previewHolder.getSurface() != null) {
try {
camera.setPreviewDisplay(previewHolder);
} catch (Throwable t) {
Log.e("PreviewDemo-surfaceCallback",
"Exception in setPreviewDisplay()", t);
Toast.makeText(CameraActivity.this, t.getMessage(),
Toast.LENGTH_LONG).show();
}
if (!cameraConfigured) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = getBestPreviewSize(width, height, parameters);
Camera.Size pictureSize = getSmallestPictureSize(parameters);
if (size != null && pictureSize != null) {
parameters.setPreviewSize(size.width, size.height);
parameters.setPictureSize(pictureSize.width,
pictureSize.height);
parameters.setPictureFormat(ImageFormat.JPEG);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
camera.setParameters(parameters);
cameraConfigured = true;
}
}
}
}
private void startPreview() {
if (cameraConfigured && camera != null) {
camera.startPreview();
inPreview = true;
}
}
SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {
// no-op -- wait until surfaceChanged()
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
initPreview(width, height);
startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
};
Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
camera.takePicture(null, null, new PhotoHandler(
getApplicationContext()));
camera.startPreview();
inPreview = true;
}
};
}
And in PhotoHandler after decoding and saving image I want to start activity
public class PhotoHandler implements PictureCallback {
private final Context context;
public PhotoHandler(Context context) {
this.context = context;
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
Log.d("", "Can't create directory to save image.");
Toast.makeText(context, "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 = "pic_" + date + ".jpg";
String pictureName = pictureFileDir.getPath() + File.separator
+ photoFile;
File pictureFile = new File(pictureName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(pictureFile);
fos.write(data);
Intent intent = new Intent(context, PreviewAndSaveActivity.class);
intent.putExtra("image", pictureName);
context.startActivity(intent);
} catch (Exception error) {
Toast.makeText(context, "Image could not be saved.",
Toast.LENGTH_LONG).show();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
}
}
}
}
private File getDir() {
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "dir");
}
}
Any suggestion what am I doing wrong?
try this code :
(Replace your button click listener )
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (camera != null) {
camera.takePicture(null, null, photoCallback);
onPause();
Intent intent = new Intent(CameraActivity.this, PreviewAndSaveActivity.class);
intent.putExtra("image", "");
CameraActivity.this.startActivityForResult(intent, 100);
}
}
});
In your CameraActivity add this callback method to redirect on another activity after image save :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
// start you new activity from here...
}
super.onActivityResult(requestCode, resultCode, data);
}
I am using camera in my application,I have no done more work on camera my requirement is only taken picture and with front and back camera and flash light.Camera will be open inside a customview for that I am using this code:-
public class CaptureDealImage extends Activity implements OnClickListener,
CameraCallback {
private Camera myCamera;
private MyCameraSurfaceView myCameraSurfaceView;
private MediaRecorder mediaRecorder;
private Button objbtncapture, objbtnback, objbtngalary, objbtnretake,
objbtnuse;
private Button objbtnflashlight, objbbtnfrontcam;// ,flashButton_p,flashButton_l,cameraRotate_p,cameraRotate_l;
private boolean recording;
private TextView show_p, show_l;
int nCurrentOrientation;
private WakeLock wakeLock;
private int count, mode;
private boolean backendCamera = true;
private FrameLayout mymiddlelayout;
private String sdcardpath;
private boolean flashlight = false;
private boolean cameramode = false;
private boolean isfrontcamera = false;
private RelativeLayout objrelativeLayoutretake, objrelativeLayout3;
private byte[] data;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dealpick);
PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = mgr
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
// Get Camera for preview
objbtnflashlight = (Button) findViewById(R.id.btnflashlight);
objbbtnfrontcam = (Button) findViewById(R.id.bbtnfrontcam);
objbtncapture = (Button) findViewById(R.id.btncapture);
objbtngalary = (Button) findViewById(R.id.btngalary);
objbtnback = (Button) findViewById(R.id.btnback);
objbtnretake = (Button) findViewById(R.id.btnretake);
objbtnuse = (Button) findViewById(R.id.btnuse);
objrelativeLayoutretake = (RelativeLayout) findViewById(R.id.relativeLayoutretake);
objrelativeLayout3 = (RelativeLayout) findViewById(R.id.relativeLayout3);
objbtnback.setOnClickListener(this);
objbtncapture.setOnClickListener(this);
objbtngalary.setOnClickListener(this);
objbtnflashlight.setOnClickListener(this);
objbbtnfrontcam.setOnClickListener(this);
objbtnretake.setOnClickListener(this);
objbtnuse.setOnClickListener(this);
}
private Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
Display getOrient = getWindowManager().getDefaultDisplay();
if (getOrient.getHeight() > getOrient.getWidth()) {
c.setDisplayOrientation(90);
}
} catch (Exception e) {
}
return c; // returns null if camera is unavailable
}
#Override
protected void onPause() {
super.onPause();
releaseCamera();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
myCamera = getCameraInstance();
if (myCamera == null) {
Toast.makeText(CaptureDealImage.this, "Fail to get Camera",
Toast.LENGTH_LONG).show();
}
myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
mymiddlelayout = (FrameLayout) findViewById(R.id.middlelayout);
mymiddlelayout.removeAllViews();
mymiddlelayout.addView(myCameraSurfaceView);
myCameraSurfaceView.setCallback(this);
}
private void releaseCamera() {
/*
* if (myCamera != null) { myCamera.release(); // release the camera for
* other applications myCamera = null; }
*/
Camera camera = this.myCameraSurfaceView.getCamera();
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
wakeLock.release();
/*
* ReleaseRootBitmap mReleaseRootBitmap=new ReleaseRootBitmap();
* LinearLayout
* mLinearLayout=(LinearLayout)findViewById(R.id.record_video_parent);
* mReleaseRootBitmap.unbindDrawables(mLinearLayout);
*/
}
public class MyCameraSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
private CameraCallback callback = null;
private boolean isStarted = true;
public MyCameraSurfaceView(Context context, Camera camera) {
super(context);
mCamera = camera;
initialize(context);
}
public MyCameraSurfaceView(Context context) {
super(context);
initialize(context);
}
public void setCallback(CameraCallback callback) {
this.callback = callback;
}
public void startPreview() {
mCamera.startPreview();
}
public void initialize(Context mcontext) {
// 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 (holder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
if (null != mCamera) {
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 {
if (null != mCamera) {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}
/*
* if (null != camera) { camera.startPreview();
*/
} catch (Exception e) {
Log.d("check",
"Error starting camera preview: " + e.getMessage());
}
}
public Camera getCamera() {
return this.mCamera;
}
public void startTakePicture() {
mCamera.autoFocus(new AutoFocusCallback() {
#Override
public void onAutoFocus(boolean success, Camera camera) {
takePicture();
}
});
}
public void takePicture() {
mCamera.takePicture(new ShutterCallback() {
#Override
public void onShutter() {
if (null != callback)
callback.onShutter();
}
}, new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (null != callback)
callback.onRawPictureTaken(data, camera);
}
}, new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (null != callback)
callback.onJpegPictureTaken(data, camera);
}
});
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
// mCamera.startPreview();
try {
mCamera.setPreviewDisplay(holder);
} catch (Throwable ignored) {
}
mCamera.setPreviewDisplay(holder);
mCamera.setPreviewCallback(new Camera.PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
if (null != callback)
callback.onPreviewFrame(data, camera);
}
});
} catch (IOException e) {
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mCamera != null) {
// camera.stopPreview();
mCamera.release();
mCamera = null;
}
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
Display display = getWindowManager().getDefaultDisplay();
if (display.getHeight() > display.getWidth()) {
myCamera.setDisplayOrientation(90);
show_l.setVisibility(View.GONE);
show_p.setVisibility(View.VISIBLE);
} else {
myCamera.setDisplayOrientation(0);
show_l.setVisibility(View.VISIBLE);
show_p.setVisibility(View.GONE);
}
}
private Handler checkHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (recording && count <= 15) {
if (mode == 1) {
show_l.setText(count + "/15");
} else {
show_p.setText(count + "/15");
}
}
}
};
#Override
public void onClick(View v) {
if (v.equals(objbtncapture)) {
myCameraSurfaceView.startTakePicture();
}
if (v.equals(objbtngalary)) {
// releaseCamera();
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
final int ACTIVITY_SELECT_IMAGE = 100;
startActivityForResult(i, ACTIVITY_SELECT_IMAGE);
}
if (v.equals(objbtnflashlight)) {
if (!isfrontcamera) {
if (!flashlight) {
flashlight = true;
Parameters params = myCamera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
myCamera.setParameters(params);
} else {
flashlight = false;
Parameters params = myCamera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
myCamera.setParameters(params);
}
}
}
if (v.equals(objbbtnfrontcam)) {
if (!cameramode) {
cameramode = true;
switchToCamera(cameramode);
} else {
cameramode = false;
switchToCamera(cameramode);
}
}
if (v.equals(objbtnback)) {
finish();
}
if (v.equals(objbtnretake)) {
objrelativeLayoutretake.setVisibility(View.GONE);
objrelativeLayout3.setVisibility(View.VISIBLE);
myCameraSurfaceView.startPreview();
}
if (v.equals(objbtnuse)) {
try {
PhotoComplete(data);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void switchToCamera(boolean frontcamera) {
releaseCamera();
if (frontcamera) {
isfrontcamera = true;
myCamera = getFrontCameraId();
} else {
isfrontcamera = false;
myCamera = getCameraInstance();
}
if (myCamera == null) {
Toast.makeText(CaptureDealImage.this, "fail to get front camera",
Toast.LENGTH_SHORT).show();
myCamera = getCameraInstance();
}
myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
mymiddlelayout = (FrameLayout) findViewById(R.id.middlelayout);
mymiddlelayout.removeAllViews();
mymiddlelayout.addView(myCameraSurfaceView);
}
Camera getFrontCameraId() {
int cameraCount = 0;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
Camera camera = null;
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
camera = Camera.open(camIdx);
Display getOrient = getWindowManager().getDefaultDisplay();
if (getOrient.getHeight() > getOrient.getWidth()) {
camera.setDisplayOrientation(90);
}
// myCamera.unlock();
// mediaRecorder.setCamera(myCamera);
// myCamera.setParameters(myCamera.getParameters());
} catch (RuntimeException e) {
Log.e("",
"Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return camera;
// No front-facing camera found
}
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
// TODO Auto-generated method stub
}
#Override
public void onShutter() {
// TODO Auto-generated method stub
}
#Override
public void onRawPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
}
#Override
public void onJpegPictureTaken(byte[] data, Camera camera) {
try {
this.data = data;
objrelativeLayoutretake.setVisibility(View.VISIBLE);
objrelativeLayout3.setVisibility(View.GONE);
} catch (Exception e) {
e.printStackTrace();
}
}
private void PhotoComplete(byte[] data) throws FileNotFoundException,
IOException {
try {
sdcardpath = String.format(getResources().getString(R.string.path),
System.currentTimeMillis());
FileOutputStream outStream = new FileOutputStream(sdcardpath);
outStream.write(data);
outStream.close();
Bundle objbundle = new Bundle();
Intent objintent = new Intent(CaptureDealImage.this,
com.flashdeal.mycamera.SetDealImageCategory.class);
objbundle.putString("from", "camera");
objbundle.putString("imagepath", sdcardpath);
Log.e("check===path", sdcardpath);
objintent.putExtras(objbundle);
startActivity(objintent);
finish();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public String onGetVideoFilename() {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bundle objbundle = new Bundle();
Intent objintent = new Intent(CaptureDealImage.this,
com.flashdeal.mycamera.SetDealImageCategory.class);
objbundle.putString("from", "camera");
objbundle.putString("imagepath", filePath);
objintent.putExtras(objbundle);
startActivity(objintent);
finish();
}
}
}
But this not work and when I click front camera ,again back camera and again on capture button camera become freez.Please anyone guide me or give imp link for my requirement.
Refer this links ::
They are facing the same issue that you have.Have a look at once .
Link 1
Link 2
Hope this helps :)