Can a custom View know that onPause has been called?
Yes you can using below code,
@Override
protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
if (visibility == View.VISIBLE) //onResume called
else // onPause() called
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
if (hasWindowFocus) //onresume() called
else // onPause() called
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
// onDestroy() called
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
// onCreate() called
}
Not unless you notify it directly.
For your purpose, override View.onDetachedFromWindow()
and relinquish your Thread there. Then, when the view is visible again, spin the Thread back up in View.onAttachedToWindow()
. The problem with onPause() and onResume() is that you can still have a view that's visible on screen, but is attached to a paused Activity. An example of when this can happen is if you have one Activity in a window that overlays another.
Or, as william gouvea suggests, a Fragment might be better suited for your purpose since it already has the life-cycle hooks for pause and resume, and anything that talks to the network really falls in the controller realm anyway.