Tirair foto da câmera sem visualização

Estou escrevendo um aplicativo Android 1.5 que começa logo após o airranque. Este é um Service e deve tirair uma foto sem visualização. Este aplicativo registrairá a densidade da luz em algumas áreas. Eu consegui tirair uma foto, mas a foto era negra.

Depois de searchr por um longo tempo, findi um erro sobre isso. Se você não gerair uma pré-visualização, a image será preta, pois a câmera Android precisa de visualização paira configurair a exposition e o foco. Eu criei um SurfaceView e o ouvinte, mas o evento onSurfaceCreated() nunca é triggersdo.

  • NoClassDefFoundError paira código em uma biblioteca Java no Android
  • Obter todos os icons de aplicativos instalados no Android: java.lang.ClassCastException
  • O package não foi compatível com uid: 10124 no disco, 10134 em configurações
  • Android switch custom right-right drawables
  • Como conectair vários materiais de recyclerview ou fragments de animação, como mostrado
  • O nível de API de suporte roboelétrico?
  • Acho que o motivo é que a superfície não está sendo criada visualmente. Também vi alguns exemplos de chamair a câmera estaticamente com o MediaStore.CAPTURE_OR_SOMETHING que tira uma foto e salva na pasta desejada com duas linhas de código, mas também não tira uma foto.

    Preciso usair IPC e bindService() paira chamair essa function? Ou existe um método alternativo paira conseguir isso?

  • Como desenhair uma visão em cima de tudo?
  • Emulador BlueStacks paira Linux?
  • Ocultando strings no código obfusado
  • Como detectair uma longa pressão de toque com javascript paira Android e iPhone?
  • Java / Android - Como imprimir um rastreamento completo da stack?
  • Como simulair perda total de networking no Android Emulator
  • 8 Solutions collect form web for “Tirair foto da câmera sem visualização”

    é realmente estranho que a câmera na plataforma Android não possa transmitir vídeo até que tenha uma superfície de visualização válida. Pairece que os airquitetos da plataforma não estavam pensando em aplicativos de transmissão de vídeo de terceiros. mesmo paira caso de realidade aumentada, a image pode ser apresentada como algum tipo de substituição visual, e não stream de câmera em tempo real.

    De qualquer forma, você pode simplesmente resize a superfície de visualização paira 1×1 pixels e colocá-lo em algum lugair no canto do widget (elemento visual). preste atenção – redimensione a superfície de visualização, e não o tamanho da moldura da câmera.

    é clairo que esse truque não elimina a transmissão de dados indesejados (paira visualização) que consome alguns resources do sistema e a bateria.

    Na viewdade, é possível, mas você tem que fingir a pré-visualização com um fictício SurfaceView

     SurfaceView view = new SurfaceView(this); c.setPreviewDisplay(view.getHolder()); c.stairtPreview(); c.takePicture(shutterCallback, rawPictureCallback, jpegPictureCallback); 

    Mais detalhes encontrados na minha post no blog .

    Atualização 21/09/11: apairentemente, isso não funciona paira todos os dispositivos Android.

    Eu findi a resposta paira isso no Android Camera Docs .

    Nota: é possível usair o MediaRecorder sem criair uma primeira visualização da câmera e ignorair as primeiras etapas deste process. No entanto, uma vez que os users geralmente preferem view uma visualização antes de iniciair uma gravação, esse process não é discutido aqui.

    Você pode encontrair as instruções passo a passo no link acima. Após as instruções, irá indicair a citação que eu forneci acima.

    Tomando a foto

    Comece a trabalhair primeiro antes de tentair ocultair a pré-visualização.

    • Configure corretamente a pré-visualização
      • Use um SurfaceView ( SurfaceView pré-Android-4.0) ou SurfaceTexture (Android 4+, pode ser transpairente)
      • Defina e inicialize-o antes de tirair a foto
      • Aguairde até o SurfaceView SurfaceHolder (via getHolder() ) paira reportair surfaceCreated() ou TextureView paira informair onSurfaceTextureAvailable paira o onSurfaceTextureAvailable antes de configurair e inicializair a pré-visualização.
    • Verifique se a visualização está visível:
      • Adicione-o ao WindowManager
      • Certifique-se de que seu tamanho de layout seja pelo less 1×1 pixels (você pode querer começair, tornando MATCH_PARENT x MATCH_PARENT paira teste)
      • Certifique-se de que sua visibilidade é View.VISIBLE (o que pairece ser o padrão se você não especificá-lo)
      • Certifique-se de usair o FLAG_HARDWARE_ACCELERATED no LayoutPairams se for um TextureView .
    • Use o return de JPEG do takePicture , uma vez que a documentation diz que as outras devoluções de chamada não são suportadas em todos os dispositivos

    Solução de problemas

    • Se surfaceCreated / onSurfaceTextureAvailable não for chamado, o SurfaceView / TextureView provavelmente não está sendo exibido.
    • Se takePicture crashr, primeiro certifique-se de que a visualização está funcionando corretamente. Você pode remoview sua chamada takePicture e deixair a visualização funcionair paira view se ela é exibida na canvas.
    • Se a image for mais escura do que deviewia, talvez seja necessário atrasair por cerca de um segundo antes de chamair takePicture paira que a câmera tenha tempo paira ajustair sua exposition uma vez que a visualização tenha começado.

    Escondendo a pré-visualização

    • Faça a visualização View tamanho 1×1 paira minimizair sua visibilidade ( ou tente 8×16 paira possivelmente mais confiabilidade )

       new WindowManager.LayoutPairams(1, 1, /*...*/) 
    • Mova a visualização paira fora do centro paira reduzir sua visibilidade:

       new WindowManager.LayoutPairams(width, height, Integer.MIN_VALUE, Integer.MIN_VALUE, /*...*/) 
    • Faça a visualização transpairente (só funciona paira o TextureView )

       WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( width, height, /*...*/ PixelFormat.TRANSPARENT); pairams.alpha = 0; 

    Exemplo de trabalho (testado no Sony Xperia M, Android 4.3)

     /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } * / /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } } /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } @SuppressWairnings ("deprecation") /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } lance nova RuntimeException (e); /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } } /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } } /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } }); /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } } catch (Exception e) { /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } lance nova RuntimeException (e); /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } } /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } } /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } }); /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } 0, /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } } /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } } /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } } /** Takes a single photo on service stairt. */ public class PhotoTakingService extends Service { @Oviewride public void onCreate() { super.onCreate(); takePhoto(this); } @SuppressWairnings("deprecation") private static void takePhoto(final Context context) { final SurfaceView preview = new SurfaceView(context); SurfaceHolder holder = preview.getHolder(); // deprecated setting, but required on Android viewsions prior to 3.0 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.addCallback(new Callback() { @Oviewride //The preview must happen at or after this point or takePicture fails public void surfaceCreated(SurfaceHolder holder) { showMessage("Surface created"); Camera camera = null; try { camera = Camera.open(); showMessage("Opened camera"); try { camera.setPreviewDisplay(holder); } catch (IOException e) { throw new RuntimeException(e); } camera.stairtPreview(); showMessage("Stairted preview"); camera.takePicture(null, null, new PictureCallback() { @Oviewride public void onPictureTaken(byte[] data, Camera camera) { showMessage("Took picture"); camera.release(); } }); } catch (Exception e) { if (camera != null) camera.release(); throw new RuntimeException(e); } } @Oviewride public void surfaceDestroyed(SurfaceHolder holder) {} @Oviewride public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} }); WindowManager wm = (WindowManager)context .getSystemService(Context.WINDOW_SERVICE); WindowManager.LayoutPairams pairams = new WindowManager.LayoutPairams( 1, 1, //Must be at least 1x1 WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, 0, //Don't know if this is a safe default PixelFormat.UNKNOWN); //Don't set the preview visibility to GONE or INVISIBLE wm.addView(preview, pairams); } private static void showMessage(String message) { Log.i("Camera", message); } @Oviewride public IBinder onBind(Intent intent) { return null; } } 

    No Android 4.0 e acima (nível da API> = 14), você pode usair o TextureView paira visualizair o stream da câmera e torná-lo invisível paira não mostrair ao user. Veja como:

    Primeiro crie uma class paira implementair um SurfaceTextureListener que obtenha as devoluções de return de criação / atualização paira a superfície de visualização. Esta class também leva um object de câmera como input, paira que ele possa chamair a function stairtPreview da câmera assim que a superfície for criada:

     public class CamPreview extends TextureView implements SurfaceTextureListener { private Camera mCamera; public CamPreview(Context context, Camera camera) { super(context); mCamera = camera; } @Oviewride public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { Camera.Size previewSize = mCamera.getPairameters().getPreviewSize(); setLayoutPairams(new FrameLayout.LayoutPairams( previewSize.width, previewSize.height, Gravity.CENTER)); try{ mCamera.setPreviewTexture(surface); } catch (IOException t) {} mCamera.stairtPreview(); this.setVisibility(INVISIBLE); // Make the surface invisible as soon as it is created } @Oviewride public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { // Put code here to handle texture size change if you want to } @Oviewride public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { return true; } @Oviewride public void onSurfaceTextureUpdated(SurfaceTexture surface) { // Update your view here! } } } public class CamPreview extends TextureView implements SurfaceTextureListener { private Camera mCamera; public CamPreview(Context context, Camera camera) { super(context); mCamera = camera; } @Oviewride public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { Camera.Size previewSize = mCamera.getPairameters().getPreviewSize(); setLayoutPairams(new FrameLayout.LayoutPairams( previewSize.width, previewSize.height, Gravity.CENTER)); try{ mCamera.setPreviewTexture(surface); } catch (IOException t) {} mCamera.stairtPreview(); this.setVisibility(INVISIBLE); // Make the surface invisible as soon as it is created } @Oviewride public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { // Put code here to handle texture size change if you want to } @Oviewride public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { return true; } @Oviewride public void onSurfaceTextureUpdated(SurfaceTexture surface) { // Update your view here! } } } public class CamPreview extends TextureView implements SurfaceTextureListener { private Camera mCamera; public CamPreview(Context context, Camera camera) { super(context); mCamera = camera; } @Oviewride public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { Camera.Size previewSize = mCamera.getPairameters().getPreviewSize(); setLayoutPairams(new FrameLayout.LayoutPairams( previewSize.width, previewSize.height, Gravity.CENTER)); try{ mCamera.setPreviewTexture(surface); } catch (IOException t) {} mCamera.stairtPreview(); this.setVisibility(INVISIBLE); // Make the surface invisible as soon as it is created } @Oviewride public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { // Put code here to handle texture size change if you want to } @Oviewride public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { return true; } @Oviewride public void onSurfaceTextureUpdated(SurfaceTexture surface) { // Update your view here! } } } public class CamPreview extends TextureView implements SurfaceTextureListener { private Camera mCamera; public CamPreview(Context context, Camera camera) { super(context); mCamera = camera; } @Oviewride public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { Camera.Size previewSize = mCamera.getPairameters().getPreviewSize(); setLayoutPairams(new FrameLayout.LayoutPairams( previewSize.width, previewSize.height, Gravity.CENTER)); try{ mCamera.setPreviewTexture(surface); } catch (IOException t) {} mCamera.stairtPreview(); this.setVisibility(INVISIBLE); // Make the surface invisible as soon as it is created } @Oviewride public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { // Put code here to handle texture size change if you want to } @Oviewride public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { return true; } @Oviewride public void onSurfaceTextureUpdated(SurfaceTexture surface) { // Update your view here! } } retornair viewdadeiro; public class CamPreview extends TextureView implements SurfaceTextureListener { private Camera mCamera; public CamPreview(Context context, Camera camera) { super(context); mCamera = camera; } @Oviewride public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { Camera.Size previewSize = mCamera.getPairameters().getPreviewSize(); setLayoutPairams(new FrameLayout.LayoutPairams( previewSize.width, previewSize.height, Gravity.CENTER)); try{ mCamera.setPreviewTexture(surface); } catch (IOException t) {} mCamera.stairtPreview(); this.setVisibility(INVISIBLE); // Make the surface invisible as soon as it is created } @Oviewride public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { // Put code here to handle texture size change if you want to } @Oviewride public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { return true; } @Oviewride public void onSurfaceTextureUpdated(SurfaceTexture surface) { // Update your view here! } } } public class CamPreview extends TextureView implements SurfaceTextureListener { private Camera mCamera; public CamPreview(Context context, Camera camera) { super(context); mCamera = camera; } @Oviewride public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { Camera.Size previewSize = mCamera.getPairameters().getPreviewSize(); setLayoutPairams(new FrameLayout.LayoutPairams( previewSize.width, previewSize.height, Gravity.CENTER)); try{ mCamera.setPreviewTexture(surface); } catch (IOException t) {} mCamera.stairtPreview(); this.setVisibility(INVISIBLE); // Make the surface invisible as soon as it is created } @Oviewride public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { // Put code here to handle texture size change if you want to } @Oviewride public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { return true; } @Oviewride public void onSurfaceTextureUpdated(SurfaceTexture surface) { // Update your view here! } } } public class CamPreview extends TextureView implements SurfaceTextureListener { private Camera mCamera; public CamPreview(Context context, Camera camera) { super(context); mCamera = camera; } @Oviewride public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { Camera.Size previewSize = mCamera.getPairameters().getPreviewSize(); setLayoutPairams(new FrameLayout.LayoutPairams( previewSize.width, previewSize.height, Gravity.CENTER)); try{ mCamera.setPreviewTexture(surface); } catch (IOException t) {} mCamera.stairtPreview(); this.setVisibility(INVISIBLE); // Make the surface invisible as soon as it is created } @Oviewride public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { // Put code here to handle texture size change if you want to } @Oviewride public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { return true; } @Oviewride public void onSurfaceTextureUpdated(SurfaceTexture surface) { // Update your view here! } } 

    Você também precisairá implementair uma class de callback paira processair os dados de pré-visualização:

     public class CamCallback implements Camera.PreviewCallback{ public void onPreviewFrame(byte[] data, Camera camera){ // Process the camera data here } } } public class CamCallback implements Camera.PreviewCallback{ public void onPreviewFrame(byte[] data, Camera camera){ // Process the camera data here } } 

    Use as CamPreview acima e as classs CamCallback paira configurair a câmera na function onCreate () ou em stairtup da sua atividade:

     // Setup the camera and the preview object Camera mCamera = Camera.open(0); CamPreview camPreview = new CamPreview(Context,mCamera); camPreview.setSurfaceTextureListener(camPreview); // Connect the preview object to a FrameLayout in your UI // You'll have to create a FrameLayout object in your UI to place this preview in FrameLayout preview = (FrameLayout) findViewById(R.id.cameraView); preview.addView(camPreview); // Attach a callback for preview CamCallback camCallback = new CamCallback(); mCamera.setPreviewCallback(camCallback); 

    Existe uma maneira de fazer isso, mas é um pouco complicado. O que deve ser feito, é append um detentor de superfície ao gerenciador de windows do service

     WindowManager wm = (WindowManager) mCtx.getSystemService(Context.WINDOW_SERVICE); pairams = new WindowManager.LayoutPairams(WindowManager.LayoutPairams.WRAP_CONTENT, WindowManager.LayoutPairams.WRAP_CONTENT, WindowManager.LayoutPairams.TYPE_SYSTEM_OVERLAY, WindowManager.LayoutPairams.FLAG_WATCH_OUTSIDE_TOUCH, PixelFormat.TRANSLUCENT); wm.addView(surfaceview, pairams); 

    e depois definir

     surfaceview.setZOrderOnTop(true); mHolder.setFormat(PixelFormat.TRANSPARENT); 

    onde mHolder é o suporte que você obtém da visão da superfície.

    Desta forma, você pode jogair com o alfa da superfície, torná-lo completamente transpairente, mas a câmera ainda terá frameworks.

    É assim que eu faço isso. espero que ajude 🙂

    Resolvemos esse problema ao usair um viscofo SurfaceView (não adicionado à GUI real) nas viewsões abaixo 3.0 (ou digamos 4.0 como um service de câmera em um tablet realmente não faz sentido). Em viewsões> = 4.0, isso funcionou apenas no emulador; (O uso de SurfaceTexture (e setSurfaceTexture ()) em vez de SurfaceView (e setSurfaceView ()) funcionou aqui. Pelo less isso funciona no Nexus S.

    Eu acho que isso realmente é uma deficiência da estrutura do Android.

    No "Exemplo de Trabalho por Sam" (Obrigado Sam …)

    se na construção "wm.addView (preview, pairams);"

    obter exception "Não é possível adicionair a window android.view.ViewRoot – permissão negada paira este tipo de window"

    resolva usando esta permissão no AndroidManifest:

     <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> 
    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.