46

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.

7 Answers 7

69

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
}
5
  • 5
    The attached/detached lifecycle does not strictly mimic the create/destroy lifecycle. But yes, if a view is attached than its activity has been created. However, after a view has been detached, its activity is not guaranteed to be destroyed. Try toggling the recents menu.
    – dcow
    Commented Sep 19, 2016 at 22:40
  • 4
    Beware: window loses focus (and the onWindowFocusChanged(false) is called) also when the Activity Options menu overflow popup is shown. I used to refresh ListView in onWindowFocusChanged() which had an unfortunate side effect of losing selected items, which is annoying especially in overflow menu in ActionMode. So, I'm thinking of employing Application.registerActivityLifecycleCallbacks() and doing some sort of callback on all views which are interested (e.g. by implementing some interface). Commented Mar 27, 2017 at 3:15
  • 3
    The provided code might have potential issues: It might get multiple onPause, onResume events. e.g. view visibility has beed changed to Invisible and afterwards window looses it's focus, The view will get 2 onPause. Commented Apr 2, 2018 at 12:08
  • Add solution and update answer, i will approve your changes Commented Apr 3, 2018 at 5:41
  • Perfect trick thank you; To add some information on when those methods are called:* LifeCycle of the view when switching app (so onPause/onResume is called at the activity level) * Quitting the application: * E/PictureChooser: onWindowFocusChanged FALSE case * E/PictureChooser: onVisibilityChanged GONE case * Going back in it: * E/PictureChooser: onVisibilityChanged VISIBLE case * E/PictureChooser: onWindowFocusChanged TRUE case Commented Jan 23, 2020 at 9:29
19

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.

1
  • 3
    onDetachedFromWindow() isn't necessarily called when an app is backgrounded by pressing the Home button. Commented Sep 14, 2017 at 16:13
11

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.

9

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();
}
2

Either you have to let your view know that the owning Activity is not in the foreground any more, or poll the system with some method to query about which task is currently in the foreground, which seems highly inefficient.

Here are two links that have addressed this issue:

(This might not really be an answer, but it was too large for a comment)

2

If you simply override the View class and create your own CustomView you could create a interface to act as a listener, which should be implemented by you parent activity, so when something happens you trigger the event and establish the communication between those components back and forth.

Depending on what you want to achieve, Fragments could be useful since this component has your own lifecycle similar to activity (onPause/onResume for instance) , holds your own state, either has or not a view and could retain their state between configuration chamges.

See more in: http://developer.android.com/reference/android/app/Fragment.html http://developer.android.com/guide/components/fragments.html

0

Using LifecycleOwner

You should implement this with androidx.lifecycle.LifecycleOwner and register it on initialisation.

For more info see https://developer.android.com/reference/android/arch/lifecycle/DefaultLifecycleObserver

An example of a custom view in Kotlin:

import android.content.Context
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import android.util.AttributeSet
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout

class YourCustomView : ConstraintLayout, DefaultLifecycleObserver {

    constructor(context: Context) : super(context) {
        initAttributes()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initAttributes(attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initAttributes(attrs, defStyleAttr, defStyleAttr)
    }

    init {
        inflate(context, R.layout.your_custom_layout, this)
        // makes this view lifecycle aware
        (context as? LifecycleOwner)?.lifecycle?.addObserver(this)
    }

    // region next hook into the lifecycle methods you need

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
    }

    // endregion

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.