Often times you will run into a scenario where you will need to signal that an event has happened, or will need to accomplish the same specific task in multiple activities. Since writing duplicate code is poor practice, you can use the common "listener" or "observer" pattern as a means to solve both of these issues. The steps below will show you how to implement this pattern.
Step 1: Define interface
public interface EventListener { void onEventHappened(); }
Step 2: In a worker class, define an instance of EventListener and create a setter. Then create a public method where the EventListener object will call the callback method in the calling activity.
public class WorkerClass { private EventListener listener; // Create setter for the listener public void setListener(EventListener listener) { this.listener = listener; } public void doWork() {
// ... do calculations, make network call, etc. here
// This will trigger onEventHappened() in CallingActivity listener.onEventHappened("Work was done!"); } }
Step 3: Create a WorkerClass variable and set the listener. You can now call doWork(), which will contains a method call to trigger onEventHappened() (your callback method).
public class CallingActivity implements EventListener { WorkerClass worker = new WorkerClass();
// Pass in 'this' to setListener()
worker.setListener(this); // Call the worker method in WorkerClass
worker.doWork(); @Override public void onEventHappened(String string) { // This method called from doWork() method in WorkerClass Log.d(TAG, string); } }
Now you're ready to create other classes/activities/fragments that can implement this. And that's it!
No comments:
Post a Comment