Reputation: 7856
I was reviewing code from a chat demo application and I noticed that they created a class that extended Application, and inside the onCreate() was the following line
registerActivityLifecycleCallbacks(new ActivityLifecycleHandler());
I then looked at the ActivityLifecycleHandler class and there were methods like
public void onActivityDestroyed(Activity activity) {
}
public void onActivityPaused(Activity activity) {
}
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
public void onActivityStarted(Activity activity) {
}
Then in all the Activity class files, in onPause()--also in onStart(), onResume(), ect--for example the lifecycle from the Application class would be referenced.
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Application.activityPaused();
}
I would like to know what this is and what it does? Does this mean that onPause() is for the Activity and Application.acitvityPaused() is for the entire application? Are their any advantages to doing this? I do not understand what the point of this is. Thanks in advance.
Upvotes: 1
Views: 1261
Reputation: 14472
I don't know, but have just Googled. Check the source.
You can see that all this does is call your callback methods, there is no further processing. The comments also indicate that it's designed usage is for handling state persistence.
Therefore, you could achieve the same by creating an Activity base class which provides overrides of the activity callbacks then extend all of your activities from this.
public class BaseActivity extends Activity{
@override
public void onCreate(){
super.onCreate(); // calls the framework method
}
}
public class Activity1 extends BaseActivity{
@override
public void onCreate(){
super.onCreate(); // calls the base method which in turn calls the framework method
...
}
}
public class Activity2 extends BaseActivity{
@override
public void onCreate(){
super.onCreate();
...
}
}
These methods will be called for all activities, regardless of whether they extend a base class. So this class lifecycle will automatically make those callbacks without you having to do anything more. Note that it only extends Activity
, not BaseActivity
.
public class Activity3 extends Activity{
@override
public void onCreate(){
super.onCreate();
...
}
}
Since you cannot have multiple inheritance in Java,if an activity needed to extend something other than a base class for all activities, you would have to start chaining callbacks which could get messy quickly.
Finally, since ActivityLifecycleCallbacks
is an interface, and since you can register multiple implemenations of that interface, you could have one set of callbacks to manage application state, another to manage user state, perhaps one to manage service or resource handling and so on without having to mix that code in a single call back method.
Upvotes: 4