How to make interface to be used by Clients : Android - android

I want to create an Android framework service and publish a listener interface to update clients on updates. I don't want to make register_XX() & unregister_XX() methods for applications to provide listener reference .What i want is , applications simply implement that listener interface and without calling any register/ unregister method gets notified of changes.
How can i implement that ?

is there any good reason against register/unregister? if you call an interface *Listener, i would expect to register/unregister it (from a dev point of view).
i think you can achieve your goal with some abstract class AbstractListener, that registers itself in the constructor - but that's not nice from an architectural point of view and doesn't work around the unregistering.
e.g.
public abstract class AbstractUpdateReceiver {
public AbstractUpdateReceiver() {
register();
}
public abstract void onReceive(Update anUpdate);
// optional, only the user should react on registering
public abstract void onRegistered();
// optional, only the user should react on unregistering
public abstract void onUnregistered();
private void register() {
//...do register
onRegistered();
}
public void unregister() {
//do unregister
onUnregistered();
}
}
the on(Un)Registered calls and implementation are not necessary, if the whole registration process should be hidden from the implementing application. but for the unregistering, the user still has to call unregister(), as long as your framework doesn't provide anything like clearReceivers() or clearReceiver(AbstractUpdateReceiver receiver)
another (much) nicer solution without anything like registering/unregistering the implementation into the framework from the implementing application would be a factory doing the whole job instead of an abstract class. in that case, you have to split the abstract class into a normal class and an interface, the normal class provides and handles the registration, while the interface provides a method for onUpdateReceived. then you'll have the factory, that creates and returns the class from the framework.
public UpdateReceiver createUpdateReceiver(IUpdateReceiver wrapped) {
UpdateReceiver receiver = new UpdateReceiver(wrapped);
receiver.register(); //or register directly into a non-static factory
return receiver;
}

Related

Is there any alternative of Intent to send data for Class (Not Activity)?

Previously, I was using activities in my project and was sending data using Intent from one activity to another which works perfectly fine.
Now requirement changes, and I have to show all things on Dialogs, instead of activities, so there will separate 3-4 dialog class and single activity.
Now I want the same flow on dialog also, but there is a problem to pass data temporarily exactly how intent works!
I tried with Singleton, but the problem is it remains data until the whole lifecycle, but I don't want that.
I can't use the interface also because there are lots of things to pass.
Also, I can't use bundle fundle n all those, because this all depends on runtime, I meant it depends upon if user fill input
Question: How can I pass data from one class to another class or activity? and it should not save value for the whole lifecycle.
statically sending data is an option but its not good way, because memory to static variables is assigned at Application level and can be cleared when memory needed. The best way is to use
Object Oriented approach
For example if you have a class, You can send data in class constructor, or can send it through function call
class class1
{
public class1(Object data) { // constructor
// you can use this data
}
//// Or through function call
public void func(Object data) { // this method can be called by other classes which has its object
// you can use this data
}
}
Now lets assume you have another class
class class2
{
class1 obj = new class1(your_data_object); // if you want to send through constructor
void someMethod() {
obj.func(your_data_object); // send data whatever you want to send
}
}
Obviously your case will not be as simple as my example, but to handle complex cases you can implement interfaces.
Interface Example
define an interface
interface myListener {
public void listen(Object data);
}
now lets say you want to call class2 method from class1. then class2 must implement this interface.
public class class2 implements myListener {
#override
public void listen(Object data)
{
/// you got data here, do whatever you want to do that with that data.
}
}
Now in class1 if you have interface object you can call class2 method
interfaceRef.listen(your_data);
Try with EventBus or BroadCastReceivers to pass data accordingly in local variables.
EventBus is a publish/subscribe event bus for Android and Java. EventBus... simplifies the communication between components. decouples event senders and receivers. performs well with Activities, Fragments, and background threads.
http://greenrobot.org/eventbus
First Register to EventBus in your Activity
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
Now pass the data from anywhere ,whether it is activity/fragment/background service etc etc etc like :
EventBus.getDefault().postSticky(new MessageEvent("your data here");
Now in your activity receive this message like :
#Subscribe(sticky = true,threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
Log.e("TAG","Event Received");
Log.e("TAG",event.getData);
}

Android: What is the best way to register callbacks in multiple instances item and return onEvents to instance callback?

Background:
Nothing special, I'm using Java for Android.
Problem:
I want to allow my users to create multiple instances of an object and register a callback Interface into each instance (think of an error callback).
The object has several children/sub-children/etc... Each child can return this event.
I expect 1-10 instances in entire lifetime of app.
I'm trying to avoid using a singleton/static events listener.
Possible solutions (and reasons not to use them):
1) Register a BroadcastReceiver in each parent-object instance and allow each grand child notify the event on Intent level. This should allow the main object to notify my user about the event.
The problem is the multiple instances would require multiple BroadcastReceivers which I expect to be heavy or just less than optimal.
2) Register one BroadcastReceiver and find a way to let it decide which instance of the object should be notified of an event, and actually send it to it. The problem is that I'm not sure how to notify the objects themselves.
3) Let the callback interface pass as an argument from parent to each of the children/grandchilren/etc... But this would be messy.
4) Use something like EventBus library (which I understand would be the same thing as BroadcastReceiver, only Reflection based, thus slower).
5) Anything else?
I don't know if this is the best solution for you but I think it would work if I understand your requirements correctly.
public class Listener extends Observable implements Observer {
private List<Observer> clients = new ArrayList<>();
public void addClient(Observer client){
clients.add(client);
}
#Override
public void update(Observable o, Object arg) {
for(Observer client : clients){
client.update(o, arg); // Or whatever you need to do
}
}
public class DataSource extends Observable {
private Observer observer;
public DataSource(Observer o){
observer = o;
}
// Notify observer of changes at appropriate time
}
public class Consumer implements Observer {
public Consumer(){
Listener listener = ...;
listener.addClient(this);
}
#Override
public void update(Observable o, Object arg) {
// Handle appropriately
}
}
}
DataSource is your "sub-objects", Consumer is the end client of the events, and Listener is the class in the middle. I don't know why the clients can't directly register for events with the "sub-objects" but that is what you said! This is modeled as inner classes here for simplicity but I assume you would not do that.

public Interface for Android

I need a little help with my Interface. I think that i doesn't understand them at all.
So i created this interface to notify every classes that implements it when a certain event occurs.
public interface OnColorsChangeListener {
void onColorsChangeListener(ColorsProp colorsProp);
}
My class that hold the interface:
private OnColorsChangeListener mCallback;
... // other code
// the event occurs here so i call:
mCallback.onColorsChangeListener(mProps);
// but of course here i get an NPE becouse this is undefined in this class.. well, with some replies here i'll understand better how to use that for reach my point
The class that implements it:
public class ClassTest implements OnColorsChangeListener {
... // other code
#Override
public void onColorsChangeListener(ColorsProp colorsProp) {
Log.d(TAG, "Color changed! " + colorsProp.color);
}
i put this in 4/5 classes to be notified in the same time for the color change. I'm quite sure the reason is that I didn't understand very well how them works, so can anyone point me to the right direction? Thank you!
Explanation by example:
You have to instantiate your callback, & it has to be an instance of your class
private OnColorsChangeListener mCallback;
mCallback = new ClassTest();
mCallback.onColorsChangeListener(mProps);
However if you want multiple callbacks you will need to use the Observer pattern.
Simple example:
private List<OnColorsChangeListener> mCallbacks = new ArrayList<OnColorsChangeListener>();
mCallbacks.add(new ClassTest());
mCallbacks.add(new OtherClass());
for(OnColorsChangeListener listener : mCallbacks) {
listener.onColorsChangeListener(mProps);
}
Obviously if you have the class, somewhere else you would not new it up, you would use that reference:
mCallbacks.add(mClassTest);
Observer Pattern Wikipedia
An interface is just a way to group together a bunch of related methods. Implementing this interface then requires you to implement all the methods grouped together by the interface.
The Java Tutorials has a good read on the subject:
What is an interface?
Here's a Stackoverflow thread regarding listener interfaces in android:
How to create our own Listener interface in android?
In short, you don't use the interface directly since it only specifies which methods implementing classes are supposed to implement.

how to listen to user-defined event? (or what's the mechanism to communicate between objects)

I'm new to android (and java) and I am wondering what's the mechanism to communicate between objects? Like if I want to monitor a private member's value, if it changes, I want a method to be triggered.
I know for UI event there's event listener. But what if it's not a mouse click, but a private member's value changing? I tried intent/broadcastreceiver, but i don't think that's for what I want to do..
Thank you so much!!
You can use publisher subscriber based approach here. Your class which contains the private (Publisher) member will have a method RegisterForChange that method you will take some interface ISomeInterface as a parameter and the Subscriber class would have implemented that interface. Once there is a change in private member you can call SomeMethod method of that interface to notify the Subscriber that my private member has been changed
//pseudocode
public interface ISomeInterface
{
SomeMethod();
}
class Publisher
{
RegisterForChange(ISomeInterface inter)
{
inter.SomeMEthod();
}
//whenever there is change call
inter.SomeMethod();
}
class Subsscriber implements ISomeInterface
{
//inside this class register for change by calling
Publisher.RegsiterForChange(this);
// this method will be called whenever there is change in private member
public SomeMethod()
{
}
}

Android - Anything similar to the iPhone SDK Delegate Callbacks?

I just switched over from iPhone to Android and am looking for something similar to where in the iPhone SDK, when a class finishes a certain task, it calls delegate methods in objects set as it's delegates.
I don't need too many details. I went through the docs and didn't find anything (the closest I got was "broadcast intents" which seem more like iOS notifications).
Even if someone can point me to the correct documentation, it would be great.
Thanks!
Never mind... found the answer here :)
http://www.javaworld.com/javaworld/javatips/jw-javatip10.html
Pasting from the article so as to preserve it:
Developers conversant in the event-driven programming model of MS-Windows and the X Window System are accustomed to passing function pointers that are invoked (that is, "called back") when something happens. Java's object-oriented model does not currently support method pointers, and thus seems to preclude using this comfortable mechanism. But all is not lost!
Java's support of interfaces provides a mechanism by which we can get the equivalent of callbacks. The trick is to define a simple interface that declares the method we wish to be invoked.
For example, suppose we want to be notified when an event happens. We can define an interface:
public interface InterestingEvent
{
// This is just a regular method so it can return something or
// take arguments if you like.
public void interestingEvent ();
}
This gives us a grip on any objects of classes that implement the interface. So, we need not concern ourselves with any other extraneous type information. This is much nicer than hacking trampoline C functions that use the data field of widgets to hold an object pointer when using C++ code with Motif.
The class that will signal the event needs to expect objects that implement the InterestingEvent interface and then invoke the interestingEvent() method as appropriate.
public class EventNotifier
{
private InterestingEvent ie;
private boolean somethingHappened;
public EventNotifier (InterestingEvent event)
{
// Save the event object for later use.
ie = event;
// Nothing to report yet.
somethingHappened = false;
}
//...
public void doWork ()
{
// Check the predicate, which is set elsewhere.
if (somethingHappened)
{
// Signal the even by invoking the interface's method.
ie.interestingEvent ();
}
//...
}
// ...
}
In that example, I used the somethingHappened predicate to track whether or not the event should be triggered. In many instances, the very fact that the method was called is enough to warrant signaling the interestingEvent().
The code that wishes to receive the event notification must implement the InterestingEvent interface and just pass a reference to itself to the event notifier.
public class CallMe implements InterestingEvent
{
private EventNotifier en;
public CallMe ()
{
// Create the event notifier and pass ourself to it.
en = new EventNotifier (this);
}
// Define the actual handler for the event.
public void interestingEvent ()
{
// Wow! Something really interesting must have occurred!
// Do something...
}
//...
}
That's all there is to it. I hope use this simple Java idiom will make your transition to Java a bit less jittery.
The pendant for kotlin.
Define your interface: In my example I scan a credit card with an external library.
interface ScanIOInterface {
fun onScannedCreditCard(creditCard: CreditCard)
}
Create a class where you can register your Activity / Fragment.
class ScanIOScanner {
var scannerInterface: ScanIOInterface? = null
fun startScanningCreditCard() {
val creditCard = Library.whichScanCreditCard() //returns CreditCard model
scannerInterface?.onScannedCreditCard(creditCard)
}
}
Implement the interface in your Activity / Fragment.
class YourClassActivity extends AppCompatActivity, ScanIOInterface {
//called when credit card was scanned
override fun onScannedCreditCard(creditCard: CreditCard) {
//do stuff with the credit card information
}
//call scanIOScanner to register your interface
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val scanIOScanner = ScanIOScanner()
scanIOScanner.scannerInterface = this
}
}
CreditCard is a model and could be define however you like. In my case it includes brand, digits, expiry date ...
After that you can call scanIOScanner.startScanningCreditCard() wherever you like.
The main content of this video tutorial is to show how to use interfaces to delegate methods / data exchange between different Fragments and activities, but it is great example to learn how delegate pattern can be implemented in Java for Android.
Java callback is not the same thing like ios delegate, in ios you can use a callback almost the same way like in Android. In Android there is startActivityForResult that can help you to implement the tasks for what ios delegate is used.
I believe ListAdapter is a example of delegation pattern in Android.
Kotlin's official Delegation pattern:
interface Base {
fun print()
}
class BaseImpl(val x: Int) : Base {
override fun print() { print(x) }
}
class Derived(b: Base) : Base by b
fun main() {
val b = BaseImpl(10)
Derived(b).print()
}
See: https://kotlinlang.org/docs/delegation.html

Categories

Resources