takePicture在服务中不起作用

时间:2015-09-25 20:05:16

标签: java android

我正在尝试使用后置摄像头拍摄照片,然后使用此代码获取它的字节:

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永远不会被调用。

1 个答案:

答案 0 :(得分:0)

取自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权限才能使用,用户可能不希望允许App使用此权限。