How to listen to all notifications sended using Signal R and Android

Viewed 29

I'm trying to send a notification using SignalR with android and I was able to only send from the android app to the Server but not to receive the same data that was sent. I'm using .NET6.

This is how I'm trying to implement this.

Program Class :

builder.Services.AddSignalR();

var app = builder.Build();

app.MapHub<Notification>("/notification");

Notification Class :

public class Notification : Hub
{
    public async Task SendMessage(string user, string message)
    {
        Debug.WriteLine("Hello Debug!" + user + message);
        await Clients.Others.SendAsync("ReceiveMessage", user, message);
    }
}

In the android project, I created a class to listen and send all data.

public class SignalRListener {
private static SignalRListener instance;
HubConnection hubConnection;

public SignalRListener(Context context){
    hubConnection = HubConnectionBuilder.create("http://192.168.1.8:3000/notification").build();
    hubConnection.on("ReceiveMessage",(user,message) -> {
        Toast.makeText(context,"I'm here.",Toast.LENGTH_LONG).show();
    }, String.class, String.class);
}
public static SignalRListener getInstance(Context context) {
    if(instance == null)
        instance = new SignalRListener(context);
    return instance;
}

public boolean StartConnection(){
    if(hubConnection.getConnectionState() == HubConnectionState.DISCONNECTED){
        hubConnection.start();
        return true;
    }else {
        return false;
    }
}

public void sendToServer(String user, String message){
    if(hubConnection.getConnectionState() == HubConnectionState.CONNECTED){
        hubConnection.send("SendMessage",user, message);
    }
}

}

The sendToServer works fine and I get the user and name values, but the hubConnection.on("ReceiveMessage",(user,message) doesn't show anything.

And this is how I call.

lateinit var notification: SignalRListener;

notification = SignalRListener.getInstance(requireContext())
        notification.StartConnection()
        test.setOnClickListener {
            notification.sendToServer("Teste","Teste");
        }

The output from the API

enter image description here

0 Answers
Related