Keeping Android camera open across activities

2019-08-02 16:45发布

问题:

I'm trying to open the Android camera and keep it running in the background constantly across multiple activities for a variety of long-running frame consumers for both Glass and non-Glass devices. This means I can not simply close the camera when one activity stops and re-open it when the next one starts; it must stay open the entire time. I've tried creating a SurfaceView using the Application as the Context (rather than an Activity) and adding it directly to the WindowManager. This does let me keep the camera open, but the only if I add it as a system overlay, which renders on top of the actual activities and makes them unusable. Other things I have tried that did not work:

  • Using Activity lifecycle callbacks to find Activities as they come up and bring their content views to the front (system overlay covers all)
  • Calling SetWillNotDraw(false) and overriding the OnDraw() of a custom SurfaceView to not actually render anything
  • Calling SetWillNotDraw(false) and overriding the OnDraw() of a custom SurfaceView to render a black rectangle that covers the screen, both opaque and transparent
  • Setting the preview size to (1, 1) after opening the camera (still rendered full-screen)
  • Creating the SurfaceView using my initial Activity as the Context and adding it to WindowManager as an Application type with no-touch flags (still rendered on top even after pushing to back, and consumed input)
  • Setting the position in the WindowManager.LayoutParams to go off-screen (still rendered on screen)

I'm running out of ideas, and am not sure what I want is even possible. Any suggestions?

回答1:

Use a Service to process the preview frames outside the context of any particular Activity. To avoid the problem with hiding the SurfaceView, use a SurfaceTexture instead, and just don't connect it to anything.

See https://github.com/Affectiva/android-sdk-samples/tree/master/ServiceFrameDetectorDemo for an example of this approach.