Ali Hasanzade
Ali Hasanzade

Reputation: 43

Android send broadcast via interface

I want to share some data between class with interface I developed some codes like this :

public interface Transmission
{
    public void onBroadcastReceived(String key, String value);
}

public class Events implements Transmission
{
    protected static Events instance;

    public static Events getInstance()
    {
        if(instance == null)
        {
            instance = new Events();
        }
        return instance;
    }
    public void addBroadcast(String key, string value)
    {
        onBroadcastReceived(key, value);
    }
    @override
    public void onBroadcastReceived(String key, String value)
    {

    }
}

public class A
{
    public A()
    {
        Events.getInstance().addBroadcast("Hello", "say hello");
    }
}

public class B implements Transmission
{
    @override
    public void onBroadcastReceived(String key, String value)
    {
        Log.d(key,value);
    }
}

B b = new B();
A a = new A();

I am trying to transfer some data with interface , is this possible ?
Is this solution true ?
Will be log key and value in B class ?
Please advise

Upvotes: 2

Views: 184

Answers (1)

Muthu
Muthu

Reputation: 1022

You need to make the following changes to get it work.

 public interface Transmission
{
    public void onBroadcastReceived(String key, String value);
}

public class Events     {
    protected static Events instance;

    public static Events getInstance()
    {
        if(instance == null)
        {
            instance = new Events();
        }
        return instance;
    }
    public void addBroadcast(String key, string value,Transmission recever)
    {
        recever.onBroadcastReceived(key, value);
    }

}

public class A
{
    public A()
    {
        B b = new B();
        Events.getInstance().addBroadcast("Hello", "say hello",b);
    }
}

public class B implements Transmission
{
    @override
    public void onBroadcastReceived(String key, String value)
    {
        Log.d(key,value);
    }
}


A a = new A();

Upvotes: 1

Related Questions