2014-01-30 104 views
5

我已经实现了从后台线程拍照的服务,但照片永远不会在我的任何设备上拍摄......这里是代码(下面的日志记录输出) :Android相机无法拍摄来自后台服务的照片

public class PhotoCaptureService extends Service { 
    private static final String TAG = "PhotoCaptureService"; 

    @Override 
    public void onStart(Intent intent, int startId) { 
     super.onStart(intent, startId); 
     Log.d(TAG, "Starting the PhotoCaptureService"); 
     takePhoto(); 
    } 

    private void takePhoto() { 

     Log.d(TAG, "Preparing to take photo"); 
     Camera camera = null; 

     try { 

      camera = Camera.open(); 

     } catch (RuntimeException e) { 

      Log.e(TAG, "Camera not available", e); 
      return; 
     } 

     if (null == camera) { 

      Log.e(TAG, "Could not get camera instance"); 
      return; 
     } 

     Log.d(TAG, "Got the camera, creating the dummy surface texture"); 
     SurfaceTexture dummySurfaceTexture = new SurfaceTexture(0); 

     try { 

      camera.setPreviewTexture(dummySurfaceTexture); 

     } catch (Exception e) { 

      Log.e(TAG, "Could not set the surface preview texture", e); 
     } 

     Log.d(TAG, "Preview texture set, starting preview"); 

     camera.startPreview(); 

     Log.d(TAG, "Preview started"); 

     camera.takePicture(null, null, new Camera.PictureCallback() { 

      @Override 
      public void onPictureTaken(byte[] data, Camera camera) { 

       Log.d(TAG, "Photo taken, stopping preview"); 

       camera.stopPreview(); 

       Log.d(TAG, "Preview stopped, releasing camera"); 

       camera.release(); 

       Log.d(TAG, "Camera released"); 
      } 
     }); 
    } 

输出记录:

D/PhotoCaptureService﹕ Starting the PhotoCaptureService 
D/PhotoCaptureService﹕ Preparing to take photo 
D/PhotoCaptureService﹕ Got the camera, creating the dummy surface texture 
D/PhotoCaptureService﹕ Preview texture set, starting preview 
D/PhotoCaptureService﹕ Preview started 

在这一点上没有什么事情发生,该onPictureTaken方法不会被调用,也没有抛出错误或异常。有谁知道为什么会发生这种情况?我已经看过StackOverflow上的每一个摄像头教程,并没有任何工作。

+0

1.服务不在后台线程中运行。要使用所需的后台服务,您必须扩展IntentService。 2.请向我们提供来自异常的堆栈跟踪。 –

+0

这是他可能会得到的那种堆栈跟踪,因为我有同样的问题 – Zeeshan

+0

你有没有得到它的工作? – VickyS

回答

1

从我的经验和我读到的,虚拟SurfaceTexture策略不适用于所有手机。尝试添加一个1x1像素SurfaceView,并在SurfaceView.getHolder()onSurfaceCreated回调(通过addCallback添加)中启动预览。

有关更多信息,请参阅Taking picture from camera without preview

相关问题