Categories
android custom-view multithreading

Can a custom View know that onPause has been called?

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 kill that thread from the parent Activity (onPause) so that the Thread isn’t milling about in the background after the Activity has been backgrounded (and/or killed).

The intention here is for the custom View to be self sufficient and not need additional handling from the Activity. The way to do that would be for it to listen for when its parent was backgrounded and for it to then let the infinite sleep loop in the Thread expire. I’m not seeing a way to do that, but am hoping that I’m overlooking something.

if Build.VERSION.SDK_INT < Build.VERSION_CODES.N

@Override
protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
if (visibility == View.VISIBLE) //onResume called
else // onPause() called
}

then Build.VERSION.SDK_INT >= Build.VERSION_CODES.N

@Override
public void onVisibilityAggregated(boolean isVisible) {
super.onVisibilityAggregated(isVisible);
if (isVisible) //onresume() called
else // onPause() called
}

you can read source code of ProgressBar to get idea.