Monday, July 9, 2012

Writing camera app on Android is hard!

A few months ago I experimenting with tesseract, which is an OCR library with Android JNI wrapper.  My app would be taking picture of English words, and then translate them to Thai using the dictionary database I have already implemented for another English-Thai dictionary app.

While there are quite a few Android camera API tutorial out there, none of them is actually completed.  I found that the app worked OK until it got paused (because user switched to another app, screen went timeout, etc), and when it resumed, it would freeze.  Finally I decided to look at the source code of the official camera app.  I found that, well, it is simply impossible to write an camera app without deep insider knowledge of Android inner working. 

For example, on typical Android app, you would put stuff to, say, re-start your app again in onResume().  However, this is the comment in onResume() in Android camera app.
// Don't grab the camera if in use by lockscreen. For example, face
// unlock may be using the camera. Camera may be already opened in
// onCreate. doOnResume should continue if mCameraDevice != null.
// Suppose camera app is in the foreground. If users turn off and turn
// on the screen very fast, camera app can still have the focus when the
// lock screen shows up. The keyguard takes input focus, so the caemra
// app will lose focus when it is displayed.
See how many gotchas you have to handle within onResume() of the camera app?  This is just one function that you need to be concerned.  There are lots of gotchas all over the places.  Good thing Android is open-source, otherwise I (and most people outside Google office) will never be able to write an acceptable camera app.  The source code for Android camera app is quite huge though, since it has to handle both still picture and movie mode.

Anyway, you can get Android camera app source code here.

No comments:

Post a Comment