Fixes #139 by porting some of the changes from iOS

@march44 can you review and merge?

I did not attempt to port the refactoring related changes.

Also, I ran into issues porting one change in particular, see https://github.com/couchbase/couchbase-lite-android/issues/277

https://github.com/couchbase/couchbase-lite-android/issues/139