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 :)
Related
I want to capture image previewed in surfaceView.Capturing time is every 42 millisecond.While capturing I want to send these images to the server as byteArray at this moment.For security reason, photo cant is saved to sd.I must use this for making a video call.Can anyone help me?Pls
Button take;
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
Camera.PictureCallback jpegCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission();
surfaceView = (SurfaceView) findViewById(R.id.surface);
surfaceHolder = surfaceView.getHolder();
take = (Button) findViewById(R.id.take);
take.setOnClickListener(this);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
surfaceHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
jpegCallback = new Camera.PictureCallback() {
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);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Toast.makeText(getApplicationContext(), "Picture Saved", Toast.LENGTH_SHORT).show();
refreshCamera();
}
};
}
public void captureImage() throws IOException {
//take the picture
camera.takePicture(null, null, jpegCallback);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
// open the camera
camera = Camera.open();
} catch (RuntimeException e) {
// check for exceptions
System.err.println(e);
return;
}
Camera.Parameters param;
param = camera.getParameters();
// modify parameter
List<Camera.Size> sizes = param.getSupportedPreviewSizes();
Camera.Size selected = sizes.get(0);
param.setPreviewSize(selected.width,selected.height);
camera.setParameters(param);
try {
// The Surface has been created, now tell the camera where to draw
// the preview.
camera.setDisplayOrientation(90);
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception e) {
// check for exceptions
System.err.println(e);
return;
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
refreshCamera();
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
// stop preview and release camera
camera.stopPreview();
camera.release();
camera = null;
}
public void refreshCamera() {
if (surfaceHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception e) {
}
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
}
break;
}
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.take:{
try {
captureImage();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
So while previewing in SurfaceView I must get every 42 millis photo as byteArray and send it
I found solution to my problem. I have fixed it through setPreviewCallbackWithBuffer an onPreviewFrame.There is no need neither handler nor timer...
private Camera camera;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private ImageView endCallBtn;
private ImageView micBtn;
private ImageView visibilityBtn;
private ImageView cameraBtn;
private Boolean clickedForMic = false;
private Boolean clickedForCamera = false;
private Boolean clickedForVisiblity = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_call);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
if (Build.VERSION.SDK_INT >= 23) {
if (checkPermission()) {
Log.e("permission", "Permission already granted.");
} else {
requestPermission();
}
}
endCallBtn = (ImageView) findViewById(R.id.endCallBtn);
endCallBtn.setOnClickListener(this);
micBtn = (ImageView) findViewById(R.id.micBtn);
micBtn.setImageResource(R.drawable.ic_mic_white_48px);
micBtn.setOnClickListener(this);
visibilityBtn = (ImageView) findViewById(R.id.visibilityBtn);
visibilityBtn.setImageResource(R.drawable.ic_visibility_white_48px);
visibilityBtn.setOnClickListener(this);
cameraBtn = (ImageView) findViewById(R.id.cameraBtn);
cameraBtn.setImageResource(R.drawable.ic_camera_rear_white_48px);
cameraBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cameraBtn: {
if (clickedForCamera == false) {
if (clickedForVisiblity == true) {
Toast.makeText(VideoCallActivity.this, "Видимость камеры заблокирована", Toast.LENGTH_SHORT).show();
} else {
stopCamera();
startCameraBack();
cameraBtn.setImageResource(R.drawable.ic_camera_front_white_48px);
clickedForCamera = true;
}
} else {
if (clickedForVisiblity == true) {
Toast.makeText(VideoCallActivity.this, "Видимость камеры заблокирована", Toast.LENGTH_SHORT).show();
} else {
stopCamera();
startCameraFront();
cameraBtn.setImageResource(R.drawable.ic_camera_rear_white_48px);
clickedForCamera = false;
}
}
break;
}
case R.id.micBtn: {
if (clickedForMic == false) {
micBtn.setImageResource(R.drawable.ic_mic_off_white_48px);
micBtn.setColorFilter(Color.parseColor("#00897B"));
clickedForMic = true;
} else {
micBtn.setImageResource(R.drawable.ic_mic_white_48px);
micBtn.setColorFilter(Color.parseColor("#ffffff"));
clickedForMic = false;
}
break;
}
case R.id.endCallBtn: {
stopCamera();
finish();
overridePendingTransition(R.anim.window3, R.anim.window4);
break;
}
case R.id.visibilityBtn: {
if (clickedForVisiblity == false) {
camera.stopPreview();
visibilityBtn.setImageResource(R.drawable.ic_visibility_off_white_48px);
visibilityBtn.setColorFilter(Color.parseColor("#00897B"));
clickedForVisiblity = true;
} else {
camera.startPreview();
visibilityBtn.setImageResource(R.drawable.ic_visibility_white_48px);
visibilityBtn.setColorFilter(Color.parseColor("#ffffff"));
clickedForVisiblity = false;
}
break;
}
}
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
}
break;
}
}
private void stopCamera() {
camera.stopPreview();
camera.release();
}
private void startCameraFront() {
if (checkPermission()) {
try {
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
} catch (Exception e) {
return;
}
Camera.Parameters param;
camera.setDisplayOrientation(90);
param = camera.getParameters();
param.setPreviewFrameRate(24);
param.setPreviewFpsRange(22000, 30000);
camera.setParameters(param);
try {
camera.setPreviewDisplay(surfaceHolder);
} catch (Exception e) {
return;
}
Log.v("CameraTest", "Camera PreviewFrameRate = " + camera.getParameters().getPreviewFrameRate());
Camera.Size previewSize = camera.getParameters().getPreviewSize();
int dataBufferSize = (int) (previewSize.height * previewSize.width *
(ImageFormat.getBitsPerPixel(camera.getParameters().getPreviewFormat()) / 8.0));
camera.addCallbackBuffer(new byte[dataBufferSize]);
camera.addCallbackBuffer(new byte[dataBufferSize]);
camera.addCallbackBuffer(new byte[dataBufferSize]);
camera.setPreviewCallbackWithBuffer(new Camera.PreviewCallback() {
private long timestamp = 0;
public synchronized void onPreviewFrame(byte[] data, Camera camera) {
//Log.v("CameraTest", "Time Gap = " + (System.currentTimeMillis() - timestamp));
Log.v("CameraTest", " data: " + String.valueOf(data.length));
timestamp = System.currentTimeMillis();
try {
camera.addCallbackBuffer(data);
} catch (Exception e) {
Log.e("CameraTest", "addCallbackBuffer error");
return;
}
return;
}
});
camera.startPreview();
}
}
private void startCameraBack() {
if (checkPermission()) {
try {
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
} catch (Exception e) {
return;
}
Camera.Parameters param;
camera.setDisplayOrientation(90);
param = camera.getParameters();
//modify parameter
param.setPreviewFrameRate(30);
camera.setParameters(param);
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception e) {
Log.d("Problema", e.toString());
return;
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
startCameraFront();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
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 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.
This is the main activity where the XML file is launched: VideoCaptureActivity.java:
public class VideoCaptureActivity extends Activity
{
private static final String TAG = "VideoCaptureActivity";
Camera camera;
ImageButton recordButton;
ImageButton stopButton;enter code here
ImageButton back;
Button flash;
Button flashoff;
Button flip;
SeekBar sb;
FrameLayout cameraPreviewFrame;
CameraPreview cameraPreview;
MediaRecorder mediaRecorder;
private Spinner spinner1;
private Timer myTimer;
File file;
int currentZoomLevel = 0;
int maxZoomLevel = 0;
int MAX_ZOOM=15;
int fcamera =0;
Size temp;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
super.setContentView(R.layout.video_capture);
// this.mediaRecorder = new MediaRecorder();
// this.mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
// this.mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// this.mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
// this.mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
// this.mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
this.cameraPreviewFrame = (FrameLayout)super.findViewById(R.id.camera_preview);
this.recordButton = (ImageButton)super.findViewById(R.id.recordButton);
this.stopButton = (ImageButton)super.findViewById(R.id.stopButton);
spinner1 = (Spinner) findViewById(R.id.spinner1);
back =(ImageButton)findViewById(R.id.back);
this.flash=(Button)findViewById(R.id.flashon);
this.flashoff=(Button)findViewById(R.id.fashoff);
this.sb = (SeekBar) findViewById(R.id.seekBar1);
this.sb.setOnSeekBarChangeListener( new seekListener() );
this.toggleButtons(false);
// we'll enable this button once the camera is ready
this.recordButton.setEnabled(false);
// this.flash.setEnabled(false);
stopButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stopRecording(v);
}
});
flash.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
flashLightOn(v );
}
});
flashoff.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
flashLightOff(v );
}
});
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//DatePicker dp = (DatePicker)findViewById(R.id.datePicker1);
Intent intent = new Intent(VideoCaptureActivity.this ,MainGrid.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
}
void toggleButtons(boolean recording) {
this.recordButton.setEnabled(!recording);
this.recordButton.setVisibility(recording ? View.GONE : View.VISIBLE);
this.stopButton.setEnabled(recording);
this.stopButton.setVisibility(recording ? View.VISIBLE : View.GONE);
}
public void flashLightOn(View view) {
// this.flash.setVisibility(View.INVISIBLE);
this.flash.setVisibility(View.INVISIBLE);
try {
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
// camera = Camera.open();
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
// camera.startPreview();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Exception flashLightOn()",
Toast.LENGTH_SHORT).show();
}
}
public void flashLightOff(View view) {
// this.flash.setVisibility(View.VISIBLE);
this.flash.setVisibility(View.VISIBLE);
try {
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Exception flashLightOff",
Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onResume() {
super.onResume();
// initialize the camera in background, as this may take a while
// try {
// Camera camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
// sb.setMax(camera.getParameters().getMaxZoom());
// sb.setProgress(0);
// // Camera camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
//
// } catch (RuntimeException e) {
// Log.wtf(TAG, "Failed to get camera", e);
// }
// if (camera == null) {
// Toast.makeText(VideoCaptureActivity.this, R.string.cannot_record,
// Toast.LENGTH_SHORT).show();
// } else {
// VideoCaptureActivity.this.initCamera(camera);
// }
new AsyncTask<Void, Void, Camera>() {
#Override
protected Camera doInBackground(Void... params) {
try {
Camera camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
sb.setMax(camera.getParameters().getMaxZoom());
sb.setProgress(0);
// Camera camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
return camera == null ? Camera.open(0) : camera;
} catch (RuntimeException e) {
Log.wtf(TAG, "Failed to get camera", e);
return null;
}
}
#Override
protected void onPostExecute(Camera camera) {
if (camera == null) {
Toast.makeText(VideoCaptureActivity.this, R.string.cannot_record,
Toast.LENGTH_SHORT).show();
} else {
initCamera(camera);
}
}
}.execute();
}
void initCamera(Camera camera) {
// we now have the camera
Camera.Parameters params = camera.getParameters();
List<Size> previewSize = params.getSupportedPreviewSizes();
temp = previewSize.get(0);
// for (int i =0; i<previewSize.size(); i++)
// {
//
// }
this.camera = camera;
// create a preview for our camera
this.cameraPreview = new CameraPreview( VideoCaptureActivity.this,camera);
// add the preview to our preview frame
this.cameraPreviewFrame.addView(this.cameraPreview);
// enable just the record button
this.recordButton.setEnabled(true);
}
void releaseCamera() {
if (this.camera != null) {
// this.camera.lock(); // unnecessary in API >= 14
// //this.camera.stopPreview();
this.camera.release();
this.camera = null;
this.cameraPreviewFrame.removeView(this.cameraPreview);
}
}
void releaseMediaRecorder() {
if (this.mediaRecorder != null) {
this.mediaRecorder.reset(); // clear configuration (optional here)
this.mediaRecorder.release();
this.mediaRecorder = null;
}
}
void releaseResources() {
this.releaseMediaRecorder();
this.releaseCamera();
}
#Override
public void onPause() {
super.onPause();
this.releaseResources();
}
#Override
public void onStop()
{
super.onStop();
this.releaseCamera();
}
#Override
public void onDestroy()
{
super.onDestroy();
this.releaseCamera();
}
// gets called by the button press
public void startRecording(final View v) {
Log.d(TAG, "startRecording()");
// we need to unlock the camera so that mediaRecorder can use it\\
// this.camera.unlock(); // unnecessary in API >= 14
// now we can initialize the media recorder and set it up with our
// camera
this.camera.stopPreview();
this.camera.release();
this.mediaRecorder = new MediaRecorder();
// this.mediaRecorder.setCamera(this.camera);
this.mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
this.mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
//// this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
this.mediaRecorder.setProfile(CamcorderProfile.get(Camera.CameraInfo.CAMERA_FACING_BACK,
CamcorderProfile.QUALITY_HIGH));
// this.mediaRecorder.setVideoSize(320, 240);
// this.mediaRecorder.setVideoFrameRate(15);
// this.mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
// this.mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
// this.mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
// this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
// if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_1080P))
// this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_1080P));
// else
// if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_720P))
// this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P));
// else
// if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_480P))
// this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_480P));
this.mediaRecorder.setOutputFile(this.initFile().getAbsolutePath());
this.mediaRecorder.setPreviewDisplay(this.cameraPreview.getHolder().getSurface());
// mediaRecorder.setMaxDuration((int) 1800);
try {
//this.toggleButtons(true);
String sec=String.valueOf(spinner1.getSelectedItem()) ;
//int seconds =Integer.parseInt(sec);
String toast =String.valueOf(spinner1.getSelectedItem()) +" Recording";
Toast.makeText(this, toast, Toast.LENGTH_SHORT).show();
if(sec.equals("1")){
this.recordButton.setVisibility(View.INVISIBLE);
this.mediaRecorder.setMaxDuration(1000);
this.mediaRecorder.prepare();
// start the actual recording
// throws IllegalStateException if not prepared
this.mediaRecorder.start();
// this.recordButton.setVisibility(View.VISIBLE);
this.recordButton.setVisibility(View.VISIBLE);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stopRecording(v);
}
},1000);
}
else if(sec.equals("2")){
this.recordButton.setVisibility(View.INVISIBLE);
this.mediaRecorder.setMaxDuration(2000);
this.mediaRecorder.prepare();
// start the actual recording
// throws IllegalStateException if not prepared
this.mediaRecorder.start();
// this.recordButton.setVisibility(View.VISIBLE);
this.recordButton.setVisibility(View.VISIBLE);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stopRecording(v);
}
},2000);
}
else{
//this.mediaRecorder.setMaxDuration(5000);
this.toggleButtons(true);
this.mediaRecorder.prepare();
//start the actual recording
// throws IllegalStateException if not prepared
this.mediaRecorder.start();
// stopRecording(v);
// enable the stop button by indicating that we are recording
}
} catch (Exception e) {
Log.wtf(TAG, "Failed to prepare MediaRecorder", e);
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
this.releaseResources();
}
}
// gets called by the button press
public void stopRecording(View v) {
Log.d(TAG, "stopRecording()");
assert this.mediaRecorder != null;
try {
this.mediaRecorder.stop();
Toast.makeText(this, R.string.saved, Toast.LENGTH_SHORT).show();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
// we are no longer recording
this.toggleButtons(false);
} catch (RuntimeException e) {
// the recording did not succeed
Log.w(TAG, "Failed to record", e);
if (this.file != null && this.file.exists() && this.file.delete()) {
Log.d(TAG, "Deleted " + this.file.getAbsolutePath());
}
return;
} finally {
this.releaseMediaRecorder();
}
if (this.file == null || !this.file.exists()) {
Log.w(TAG, "File does not exist after stop: " + this.file.getAbsolutePath());
} else {
Log.d(TAG, "Going to display the video: " + this.file.getAbsolutePath());
Intent intent = new Intent(this, VideoPlaybackActivity.class);
intent.setData(Uri.fromFile(file));
super.startActivity(intent);
}
}
private File initFile() {
File dir = new File(
Environment.getExternalStorageDirectory().toString() +
Utils.OUR_TEMP_FOLDER);
if (!dir.exists() && !dir.mkdirs()) {
Log.wtf(TAG, "Failed to create storage directory: " + dir.getAbsolutePath());
Toast.makeText(VideoCaptureActivity.this, R.string.cannot_record, Toast.LENGTH_SHORT).show();
this.file = null;
} else {
this.file = new File(dir.getAbsolutePath(), new SimpleDateFormat(
"yyyyMMddHHmmss'.mp4'").format(new Date()));
}
return this.file;
}
private class seekListener implements SeekBar.OnSeekBarChangeListener
{
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser == true)
{
Parameters p = camera.getParameters();
p.setZoom(progress);
camera.setParameters(p);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
}
My camera prewiew is as follows
CameraPreview.java:
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "CameraPreview";
private final Camera camera;
#SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
Camera.Parameters params = camera.getParameters();
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO))
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
else
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO))
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
camera.setParameters(params);
this.camera = camera;
super.getHolder().addCallback(this);
// required for API <= 11
super.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated()");
// now that we have the surface, we can start the preview
try {
this.camera.setPreviewDisplay(holder);
this.camera.startPreview();
} catch (IOException e) {
Log.wtf(TAG, "Failed to start camera preview", e);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// we will release the camera preview in our activity before this
// happens
Log.d(TAG, "surfaceDestroyed()");
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// our activity runs with screenOrientation="landscape" so we don't
// care about surface changes
Parameters params = camera.getParameters();
Log.d(TAG, "surfaceChanged()");
}
}
I dont know what went wrong camera is working fine but the UI is visible at start but invisible after some time but the preview remains and if ii clicked on to the button which is invisible it works .so the control works but cant see.