3

Does anyone have a working sample of such "thing"?

In theory it's a good idea to implement it this way but I didn't see any relevant piece of code which shows how to implement it.

I don't want anything fancy, the simpler the better. I just want to have everything related to camera control implemented on a separate thread.

Thanks

[edit]

more specific: like the official documentation states, "the recommended way to access the camera is to open Camera on a separate thread that's launched from onCreate()". Therefore what I need is a minimal implementation of a CameraPreview class extending AsyncTask (I assume).

Alex Cohn
  • 56,089
  • 9
  • 113
  • 307
Traian
  • 2,915
  • 1
  • 24
  • 32

1 Answers1

2

Your quote is IIRC, incomplete. The recommendation is There are two reasons to offload camera.open() to a secondary thread. One is that open() itself is slow on some devices. But camera callbacks will still arrive on the main thread.

If you don't want to receive camera callbacks on the UI thread, you should open the camera on a separate event thread (emphasis mine). Event thread is also known as Looper thread.

Therefore AsyncTask cannot help here. See https://stackoverflow.com/a/19154438/192373 for a working example.

Community
  • 1
  • 1
Alex Cohn
  • 56,089
  • 9
  • 113
  • 307
  • In the given example you wait for the `Camera.open` to finish so essentially that doesn't help with the "offload to a secondary thread", handling those callbacks on a non UI Looper is nice, but the interesting part is getting the camera open/closed in the right times and also handling the `surfaceChanged` event correctly. Can you help regarding these? – TWiStErRob Aug 13 '14 at 23:49
  • @TWiStErRob: I am not sure I understand your question. No, there is no "wait" for the camera to complete `open()` in the UI thread. The app remains responsive all the time. I did skip error handling and in real life you need some plumbing to handle the situation when `surfaceDestroyed` happens before the camera is ready. – Alex Cohn Aug 14 '14 at 03:08
  • In `mThread.openCamera` you post a `Runnable` then immediately start waiting. When the `Camera.open` returns you `notify` this `wait`, which is almost equivalent to a `mThread.join()` (in non-Looper world). Now you call `newOpenCamera` in place of `oldOpenCamera` which was on the UI thread, so you have an item in the UI Looper which is blocking. – TWiStErRob Aug 14 '14 at 09:56
  • 1
    @TWiStErRob: Now I understand your confusion. The code I started with in [the example](http://stackoverflow.com/a/19154438/192373), already launched a worker thread to `openCamera()`. It was being launched from the `surfaceCreated()`. Naturally, you can use the Looper directly, and avoid that extra thread if you plan your system correctly up-front. – Alex Cohn Aug 14 '14 at 11:32