3

Is there a way for us to receive events such as onResume, onWindowFocusChanged, etc., from outside the activity? I would like to run some code when these events are raised in another class, which only has a reference to the activity.

EDIT: In my case, I can't modify the Activity class, or override it in a subclass.

Rudey
  • 4,717
  • 4
  • 42
  • 84

2 Answers2

1

These methods are called by the Android OS. The best you could do is for your Activity to have an instance of this other class, and you would make similar methods in that class that your Activity will call in its own lifecycle methods.

public class SomeOtherClass {
    public void onResume() {
        ...
    }

    public void onPause() {
        ...
    }

    /* other similar methods */
}

public class MyActivity extends Activity {
    private SomeOtherClass someOtherClass; // make sure to initialize this somewhere

    @Override
    protected void onResume() {
        super.onResume();
        someOtherClass.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        someOtherClass.onPause();
    }

    /* and so one */
}
Karakuri
  • 38,365
  • 12
  • 84
  • 104
  • This looks like it would be a good solution. However, in my case, I can't modify the Activity class, or override it in a subclass. Thanks though. – Rudey Apr 29 '14 at 08:00
  • 1
    Well then you might be stuck. There's a method on the Application class called `registerActivityLifecycleCallbacks()`, but it has no documentation and I don't know exactly how it works. That's the only other thing I can think of. – Karakuri Apr 29 '14 at 08:13
  • That method has a rather interesting return type. Too bad it is not documented, because it looks like it is exactly what I need. I will experiment with this. – Rudey Apr 29 '14 at 08:44
1

I ended up using Application.registerActivityLifecycleCallbacks for onResume, and Window.getCallback() for onWindowFocusChanged. Thank you @Karakuri for mentioning the first method in the comments.

Community
  • 1
  • 1
Rudey
  • 4,717
  • 4
  • 42
  • 84
  • For `onWindowFocusChanged`, this answer gives the details of how to override the window callback: https://stackoverflow.com/questions/25441531/detect-every-touch-events-without-overriding-dispatchtouchevent – frodo2975 Jan 18 '20 at 07:08