Capture image in service without preview android
I solved my issue with help of this blog
So I capture the image within background service using this code:
@Override
public void onStart(Intent intent, int startId) {
mCamera = getAvailableFrontCamera(); // globally declared instance of camera
if (mCamera == null){
mCamera = Camera.open(); //Take rear facing camera only if no front camera available
}
SurfaceView sv = new SurfaceView(getApplicationContext());
SurfaceTexture surfaceTexture = new SurfaceTexture(10);
try {
mCamera.setPreviewTexture(surfaceTexture);
//mCamera.setPreviewDisplay(sv.getHolder());
parameters = mCamera.getParameters();
//set camera parameters
mCamera.setParameters(parameters);
//This boolean is used as app crashes while writing images to file if simultaneous calls are made to takePicture
if(safeToCapture) {
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Get a surface
sHolder = sv.getHolder();
//tells Android that this surface will have its data constantly replaced
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
safeToCapture = false;
//decode the data obtained by the camera into a Bitmap
FileOutputStream outStream = null;
try{
// create a File object for the parent directory
File myDirectory = new File(Environment.getExternalStorageDirectory()+"/Test");
// have the object build the directory structure, if needed.
myDirectory.mkdirs();
//SDF for getting current time for unique image name
SimpleDateFormat curTimeFormat = new SimpleDateFormat("ddMMyyyyhhmmss");
String curTime = curTimeFormat.format(new java.util.Date());
// create a File object for the output file
outStream = new FileOutputStream(myDirectory+"/user"+curTime+".jpg");
outStream.write(data);
outStream.close();
mCamera.release();
mCamera = null;
String strImagePath = Environment.getExternalStorageDirectory()+"/"+myDirectory.getName()+"/user"+curTime+".jpg";
sendEmailWithImage(strImagePath);
Log.d("CAMERA", "picture clicked - "+strImagePath);
} catch (FileNotFoundException e){
Log.d("CAMERA", e.getMessage());
} catch (IOException e){
Log.d("CAMERA", e.getMessage());
}
safeToCapture = true; //Set a boolean to true again after saving file.
}
};
private Camera getAvailableFrontCamera (){
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());
}
}
}
return cam;
}
//Send Email using javamail API as user will not be allowed to choose available
// application using a Chooser dialog for intent.
public void sendEmailWithImage(String imageFile){
.
.
.
}
Following uses-features and permissions will be needed for this in manifest file:
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-feature
android:name="android.hardware.camera.front"
android:required="false" />
<uses-permission android:name="android.permission.SEND_MAIL" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
I have set property required
to false, so that user will be able to install my app even without any of the Camera available. May be this can help someone in future.
Take photo in background without UI. Android
Here's camera preview code that worked for me: https://stackoverflow.com/a/33242595/7391954
I overlaid my layout on it and then taking photo was as simple as calling getBitmap()
on that View.
Take a picture in background on Android
This is a snippet from a project a did before, I hope it will help you:
// Open the camera and take a picture
public void openCamera() {
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
startActivityForResult(getIntent, SEND_MESSAGE_IMG_REQUEST_IMAGE_PICK);
}
// handle the result from camera
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == SEND_MESSAGE_IMG_REQUEST_IMAGE_PICK && 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();
// do a background task to handle the captured image (upload it to a server or something like that)
}
}
Can we use takePicture() in android without camera preview? I need to take a picture secretly for security purposes
According to android.developer.com, no.
https://developer.android.com/reference/android/hardware/Camera.html
"Important: Call startPreview() to start updating the preview surface. Preview must be started before you can take a picture."
Related Topics
App Not Setup: This App Is Still in Development Mode
Official "Boost Library" Support for Android and iOS
Display Huge Images in Android
Android Navigation Architecture Component - Get Current Visible Fragment
How to Merge Call Programmatically While Other Call Is Running (Conference Call)
Broadcast Receiver Won't Receive Camera Event
Scaled Bitmap Maintaining Aspect Ratio
Android Application Class Lifecycle
Android Install on Device Failure [Install_Canceled_By_User]
Adjust Layout When Soft Keyboard Is On
Prevent Ussd Dialog and Read Ussd Response
Difference Between a Clickable Imageview and Imagebutton
How to Dynamically Set Headers in Retrofit (Android)
Android: Adding Static Header to the Top of a Listactivity
Android Location Manager, Get Gps Location ,If No Gps Then Get to Network Provider Location