我需要在Android服务中使用后置摄像头拍照,但在阅读文档后,您似乎需要SurfaceView
是否可以在不向用户显示任何内容的情况下拍照?
编辑: 这有用吗?
SurfaceTexture surfaceTexture = new SurfaceTexture(10);
Camera camera = Camera.open();
camera.getParameters().setPreviewSize(1, 1);
camera.setPreviewTexture(surfaceTexture);
camera.startPreview();
camera.takePicture(null, pictureCallback, null);
答案 0 :(得分:1)
100%正常工作。使用服务从前置摄像头点击图片。
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
CapturePhoto();
}
private void CapturePhoto() {
Log.d("kkkk","Preparing to take photo");
Camera camera = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
int frontCamera = 1;
//int backCamera=0;
Camera.getCameraInfo(frontCamera, cameraInfo);
try {
camera = Camera.open(frontCamera);
} catch (RuntimeException e) {
Log.d("kkkk","Camera not available: " + 1);
camera = null;
//e.printStackTrace();
}
try {
if (null == camera) {
Log.d("kkkk","Could not get camera instance");
} else {
Log.d("kkkk","Got the camera, creating the dummy surface texture");
try {
camera.setPreviewTexture(new SurfaceTexture(0));
camera.startPreview();
} catch (Exception e) {
Log.d("kkkk","Could not set the surface preview texture");
e.printStackTrace();
}
camera.takePicture(null, null, new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFileDir=new File("/sdcard/CaptureByService");
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
pictureFileDir.mkdirs();
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "ServiceClickedPic_" + "_" + date + ".jpg";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File mainPicture = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(mainPicture);
fos.write(data);
fos.close();
Log.d("kkkk","image saved");
} catch (Exception error) {
Log.d("kkkk","Image could not be saved");
}
camera.release();
}
});
}
} catch (Exception e) {
camera.release();
}
}
}
答案 1 :(得分:0)
您可以将Width
的{{1}}和Height
设置为SurfaceView
,将1dp
设置为 - margintop
,以便它不会显示在屏幕,但它正常运行,您可以拍照而不显示用户的表面视图
10
在这种情况下,您可以使用<SurfaceView
android:layout_width="1dp"
android:layout_height="1dp"
android:layout_marginTop="-10dp"
...
/>
SurfaceTexture
答案 2 :(得分:0)
是的,这是可能的。调用您的相机回调方法从相机拍摄照片,然后不要指定预览尺寸,然后开始预览就可以了。
省略这一步:
param.setPreviewSize(122,133);
或使用
param.setPreviewSize(1, 1);