Skip to content

Instantly share code, notes, and snippets.

@jamiesanson
Created June 21, 2018 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiesanson/9535a8449ad4fce4733a134d69e4207a to your computer and use it in GitHub Desktop.
Save jamiesanson/9535a8449ad4fce4733a134d69e4207a to your computer and use it in GitHub Desktop.
Lifecycle-aware CameraView implementation
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.OnLifecycleEvent
import android.content.Context
import android.util.AttributeSet
import com.wonderkiln.camerakit.*
/**
* Lifecycle aware view subclass of CameraView to allow automatic starting and stopping on lifecycle
* events
*/
class LifecycleCameraView(context: Context, attributeSet: AttributeSet): CameraView(context, attributeSet), LifecycleObserver {
var isStopped = true
private set
private var lifecycle: Lifecycle? = null
fun init(owner: LifecycleOwner) {
lifecycle = owner.lifecycle
owner.lifecycle.addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
if (isStopped) {
this.start()
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
if (!isStopped) {
this.stop()
}
}
override fun stop() {
if (lifecycle?.currentState?.isAtLeast(Lifecycle.State.CREATED) == true) {
super.stop()
isStopped = true
}
}
override fun start() {
if (lifecycle?.currentState?.isAtLeast(Lifecycle.State.CREATED) == true) {
super.start()
isStopped = false
}
}
fun onPictureTaken(callback: (jepg: ByteArray) -> Unit) {
this.addCameraKitListener(object: CameraKitEventListener {
override fun onVideo(p0: CameraKitVideo?) {}
override fun onEvent(p0: CameraKitEvent?) {}
override fun onImage(image: CameraKitImage?) {
image?.jpeg?.let(callback)
}
override fun onError(p0: CameraKitError?) {}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment