Reputation: 2082
One of the classes I've written needs to react when the following Activity
events occur:
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.
Upvotes: 8
Views: 5107
Reputation: 14271
Leverage ActivityLifecycleCallbacks that has been introduced since API level 14.
This is what the interface looks like now.
public interface ActivityLifecycleCallbacks {
void onActivityCreated(Activity activity, Bundle savedInstanceState);
void onActivityStarted(Activity activity);
void onActivityResumed(Activity activity);
void onActivityPaused(Activity activity);
void onActivityStopped(Activity activity);
void onActivitySaveInstanceState(Activity activity, Bundle outState);
void onActivityDestroyed(Activity activity);
}
What you need to do is simply to implement the interface methods and register it on your application.
public class MyApplication extends Application implements ActivityLifecycleCallbacks {
@Override
public void onCreate() {
super.onCreate();
this.registerActivityLifecycleCallbacks(this);
}
//implement call back methods.
}
Upvotes: 0
Reputation: 1984
You can use this library that does exactly what you're trying to do, without having to write code in your activity or in your base activity.
And is very simple to use:
ActivityListener.bind(mActivity).with(mCallback);
Maybe it helps someone
Upvotes: -1
Reputation: 1103
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.
Upvotes: 7