我正在尝试使用后置摄像头拍照,然后在使用此代码的服务中获取字节数:
Camera camera = Camera.open();
SurfaceView view = new SurfaceView(getApplicationContext());
SurfaceHolder holder = view.getHolder();
camera.getParameters().setPreviewSize(1, 1);
camera.setPreviewDisplay(holder);
camera.startPreview();
camera.takePicture(null, pictureCallback, null);
但这是行不通的。我没有收到异常,但从未调用pictureCallback。
最佳答案
取自android docs:http://developer.android.com/training/camera/photobasics.html
您应该这样调用相机意图:
首先在androidmanifest文件中为您的应用添加必要的权限:
<manifest ... >
<uses-feature android:name="android.hardware.camera"
android:required="true" />
...
</manifest>
之后,调用相应的意图启动摄像头:
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
从相机接收到的数据将通过以下方法调用,您可以在其中存储或使用它:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
如果要在服务中实现此功能,请从此link中获取代码,则应该可以从服务中拍照:
mPreview = new CameraPreview(this, mCamera, jpegCallback);
WindowManager wm = (WindowManager) this
.getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSPARENT);
params.height = 1;
params.width = 1;
wm.addView(mPreview, params);
如评论所述,请注意,这需要权限SYSTEM_ALERT_WINDOW才能起作用,用户可能不希望允许应用使用此权限。