Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an object listen to Activity lifecycle events?

One of the classes I've written needs to react when the following Activity events occur:

  • onStart()
  • onPause()
  • onResume()
  • onStop()

I can react to those on the Activity itself:

public class Activity extends ApplicationContext
{
    protected void onCreate(Bundle savedInstanceState);

    protected void onStart();

    protected void onRestart();

    protected void onResume();

    protected void onPause();

    protected void onStop();

    protected void onDestroy();
}

From the Activity I could tell the object in question that a certain event has occurred, but I don't like this idea: it requires the developer to implement the logic outside my object/class. Ideally I would like the object to be responsible for registering these events and set itself as a listener, independent of the Activity.

Any ideas? Thanks in advance.

like image 375
titusmagnus Avatar asked Apr 01 '11 00:04

titusmagnus


People also ask

What is onSaveInstanceState () and onRestoreInstanceState () in activity?

The onSaveInstanceState() method allows you to add key/value pairs to the outState of the app. Then the onRestoreInstanceState() method will allow you to retrieve the value and set it back to the variable from which it was originally collected.

When an activity is created what method that automatically invoked?

The onCreate() callback is compulsory in all Android applications. It is the first method called when we launch an activity from the home screen or intent. In other words, it is a default callback that is automatically created when you create a new activity.


1 Answers

API level 14 has Application.ActivityLifecycleCallbacks.
Before that, afaik, sorry, no.
If you wish to offer your class to others, you will need to either provide abstract classes that extend the most common Activities, or have them put certain calls in their own Activity's lifecycle methods, like

protected void onPause() {
  super.onPause();
  yourClassInstance.onPause();
}

May as well make it more general, and create abstract NotifyingActivity classes that accept NotifyingActivity.LifecycleListener's, and make your class implement such a listener and register itself in its constructor.

like image 157
kaay Avatar answered Nov 14 '22 23:11

kaay