I have a custom View that runs a Thread operation which sits around making calls to the interwebs periodically. I would like to know if there\'s a way for me to not have to kil
Yes you can. All that you need is to have a field of LifecycleOwner type. More about it in official documentation. In my case i created a custom view with another view from 3rd party library - CameraView.
At first, custom view needs to implement LifecycleOberver interface
public class MakePhotoView extends ConstraintLayout implements LifecycleObserver
So, i have a field in my custom view:
private LifecycleOwner mLifecycleOwner;
I pass it in the constructor as one of parameters:
public MakePhotoView(Context context, OnPhotoMadeListener onPhotoMadeListener, LifecycleOwner lifecycleOwner) {
super(context);
mOnPhotoMadeListener = onPhotoMadeListener;
mLifecycleOwner = lifecycleOwner;
init();
}
After that i register my custom view as observer for lifecycle events in LifecycleOwner:
private void init() {
//other code
mLifecycleOwner.getLifecycle().addObserver(this);
}
And finally i can listen for lifecycle events:
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void startCamera() {
AppLog.logObject(this, "On Resume called for MakeCameraView");
mCameraView.start();
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void stopCamera() {
AppLog.logObject(this, "On Pause called for MakeCameraView");
mCameraView.stop();
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void destroyCamera() {
AppLog.logObject(this, "On Destroy called for MakeCameraView");
mCameraView.destroy();
}