Registering for an activity's events

android, android-activity, android-event

Solution

One way to get events from the lifecycle of other activities is to register your class as an `Application.ActivityLifecycleCallbacks` with the main `Application` instance and filter events for the `Activity` you're interested in.

This is a short example (you may want to register the callbacks from another method/class other than `MainActivity.onCreate` or you'll miss that message ;) and you may have a dependency there that you don't want)

On the activity you want to spy:

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Register a spy for this activity
        getApplication().registerActivityLifecycleCallbacks(new ActivitySpy(this));
    }
}

Then the Spy code looks something like:

public class ActivitySpy implements ActivityLifecycleCallbacks {

    private final Activity mActivity;

    public ActivitySpy(Activity activity) {
        mActivity = activity;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        if (mActivity == activity)
            Log.i("SPY", "Activity Created");
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        if (mActivity == activity)
            Log.i("SPY", "Activity Destroyed");
    }

    // (...) Other overrides

}

You can also register the spy from another place if you have a reference to the Activity you want to follow.

I hope this helps :)

EDIT: I forgot to mention, this will only work on API Level 14 and above...

Problem

Is there a way to register for an activity's events? I'm specifically interested in the onStart / onStop events, and I don't want to add special operations in the activity for that.

Original source